Essential Shell Script Style Guide: Best Practices and Tips
This guide consolidates practical conventions for writing clean, maintainable shell scripts, covering shebang usage, commenting, parameter validation, variable handling, indentation, naming, encoding, efficiency tricks, and static analysis with ShellCheck.
Due to work requirements the author revisited shell scripting and found that scripts often become unreadable, lack consistent style, and suffer from version differences; therefore a set of conventions is presented to serve as a personal technical standard.
Shebang and Interpreter Selection
Include a shebang (e.g., #!/bin/bash) at the script top to specify the interpreter. Without it, the script runs with the shell defined by $SHELL. List available interpreters via cat /etc/shells.
Comments
Comments act as a README for each script, explaining purpose, parameters, usage, warnings, author, timestamps, and function descriptions. A typical comment list includes shebang, parameters, purpose, cautions, author/license, and per‑function notes.
Parameter Validation
Validate argument count and values early, providing clear error messages, e.g.:
if [[ $# != 2 ]]; then
echo "Parameter incorrect."
exit 1
fiVariables and Magic Numbers
Define important environment variables at the script start and avoid hard‑coded literals; use variables instead. Example of setting PATH and sourcing /etc/profile is shown.
Indentation
Use consistent indentation (soft tabs with 2 or 4 spaces or hard tabs). Keep then and do on the same line as the condition to improve readability.
Naming Conventions
File names end with .sh.
Variable names are meaningful, lowercase with underscores.
Functions follow func_name() syntax.
Encoding
Prefer UTF‑8 without BOM; avoid Chinese characters in logs/comments to prevent garbled output. Convert line endings with dos2unix / unix2dos when needed.
Permissions
Remember to set executable permission ( chmod +x script.sh).
Logging and Echo
Provide runtime logs and echo progress for user feedback. Use ANSI/VT100 sequences for colored output if desired.
Avoid Hard‑Coded Passwords
Never embed passwords in scripts; keep them out of version control.
Line Continuation
Break long commands with a backslash preceded by a space:
./configure \
--prefix=/usr \
--sbin-path=/usr/sbin/nginx \
--conf-path=/etc/nginx/nginx.conf \Efficiency Tips
Choose commands that minimize passes over data (e.g., sed -n '1p;1q' vs. sed -n '1p') and combine multiple sed expressions into one to reduce process spawning. Use xargs -P $(nproc) for parallel execution.
Parallel Execution
Run functions in background with & and synchronize with wait, or use parallel / xargs for more control.
Full‑Text Search
Search across files safely handling spaces and binary files using find … -type f | xargs -i echo "{}" | xargs grep pattern or adding -a to grep.
Modern Syntax Recommendations
Define functions with func(){ … } rather than func{ … }.
Prefer [[ … ]] over [ … ].
Use $(command) instead of backticks.
Prefer printf over echo for complex output.
Additional Tips
Prefer absolute paths; if relative, prefix with ./.
Use Bash parameter expansion instead of external awk / sed when possible.
Write simple if statements as single‑line [[ condition ]] && echo ….
Namespace exported variables to avoid clashes.
Use trap for cleanup on termination.
Create temporary files with mktemp.
Redirect unwanted output to /dev/null.
Check command exit status to handle errors.
Test file existence before operating on it.
Avoid parsing ls output; use globbing or find instead.
Read files with while read loops rather than for over lines.
Be aware of cp -r behavior regarding destination directories.
Static Analysis with ShellCheck
ShellCheck is an open‑source static analysis tool (GitHub) with wide platform support (Debian, Arch, Fedora, macOS, etc.). Install via package manager, integrate into CI pipelines (e.g., Travis CI), and consult its extensive wiki for detailed explanations of each warning and recommended fixes.
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.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
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.
