Mastering Shell Script Style: Essential Guidelines for Clean, Efficient Bash Code
This article compiles comprehensive shell scripting best‑practice guidelines—including shebang usage, commenting, parameter validation, variable handling, indentation, naming conventions, encoding, permissions, logging, password safety, line continuation, efficiency tricks, quoting, function structuring, scope control, indirect references, heredocs, path resolution, parallel execution, modern syntax, and static analysis with ShellCheck—to help developers write readable, maintainable, and performant Bash scripts.
Preface
Due to work needs, the author revisited shell scripting and found that scripts often look messy and hard to read, resembling a long main function. Because shell scripts are more like tools than formal programming languages, many developers write them ad‑hoc, leading to inconsistent style across different versions and commands.
After researching existing documents, the author organized scattered advice into a concise technical specification for future script writing.
Code Style Guidelines
Shebang
The shebang ("#!") on the first line specifies the interpreter when none is explicitly given. A recommended portable shebang is shown in the image below.
Comments
Comments are essential in shell scripts to explain purpose, parameters, usage, warnings, author information, and function details. Typical comment sections include shebang, script parameters, purpose, cautions, metadata, and per‑function explanations.
shebang
script parameters
script purpose
script cautions
author, time, copyright
function pre‑comments
complex one‑liner comments
Parameter Validation
When a script accepts arguments, always validate them and provide helpful messages, starting with a check for the number of parameters.
Variables and Magic Numbers
Define important environment variables at the top, such as JAVA_HOME and PATH, and avoid hard‑coded magic numbers; use named variables instead.
Indentation
Proper indentation (soft tabs with 2 or 4 spaces, or hard tabs) improves readability, especially inside functions and control structures.
soft tab: use n spaces (commonly 2 or 4)
hard tab: use the literal tab character
Naming Conventions
File names should end with .sh, variable names should be meaningful and use lowercase with underscores.
file name ends with .sh
meaningful variable names
lowercase with underscores
Encoding
Prefer UTF‑8 without BOM; avoid Chinese characters in comments and logs to prevent garbled output on systems lacking proper locale support.
Permissions
Remember to add execute permission to scripts; otherwise they cannot be run directly.
Logging and Echo
Logging is crucial for debugging; provide real‑time echo output for user‑facing scripts, optionally using ANSI color codes for better UX.
Password Handling
Never hard‑code passwords in scripts; especially important for code hosted on public platforms like GitHub.
Line Continuation
Use a backslash followed by a space to split long command lines for readability.
Efficiency Tips
Prefer single commands over multiple ones; choose commands that read only what is necessary (e.g., head -n1 instead of sed that reads the whole file). Use xargs -P for parallel processing.
Quoting
Always double‑quote variable expansions to avoid word splitting and globbing issues.
Using a Main Function
Encapsulate script logic inside a main() function and call it at the end to improve structure.
Scope Considerations
Shell variables are global by default; use local and readonly or declare to limit scope.
Function Return Values
Functions return integer status codes; to return strings, echo the value and capture it.
Indirect References
Use ${!VAR} for simple indirect variable expansion; avoid eval when possible.
Heredocs
Heredocs ( <<EOF) allow multi‑line input, useful for generating template files.
Path Lookup
Use $(cd "$(dirname "$0")" && pwd) or realpath "$0" to obtain the script’s directory rather than relying on pwd.
Keeping Code Short
Prefer fewer commands; combine operations when possible to improve both readability and performance.
Command Parallelization
Use & and wait for simple parallelism, or parallel for more control.
Modern Syntax
Adopt newer Bash features: func() {} instead of func{}, [[ ]] over [ ], $( ) over backticks, and printf instead of echo for complex output.
Other Tips
Prefer absolute paths; if using relative paths, prefix with ./.
Prefer Bash parameter expansion over awk / sed for simple tasks.
Write simple if statements using && and || on a single line.
Namespace exported variables to avoid clashes.
Use trap to handle termination signals.
Generate temporary files with mktemp.
Redirect unwanted output to /dev/null.
Check file existence before operating on it.
Avoid parsing ls output.
Read files with while read loops instead of for over lines.
Static Analysis Tool: ShellCheck
Overview
ShellCheck is an open‑source static analysis tool for shell scripts, widely used and available on many platforms.
Installation
It can be installed via package managers on Debian, Arch, Gentoo, EPEL, Fedora, macOS, openSUSE, etc.
Integration
ShellCheck integrates easily into CI pipelines such as Travis CI for automated script linting.
Examples
The tool’s “Gallery of bad code” provides concrete examples of common pitfalls and their fixes.
Core Value
The most valuable part is its extensive wiki, which explains each warning, why it matters, and the recommended fix, making it ideal for developers who want to deepen their understanding of shell best practices.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
