Mastering Shell Script Style: Essential Guidelines for Clean, Efficient Code
This article compiles comprehensive shell scripting style guidelines—including shebang usage, commenting standards, parameter validation, variable handling, indentation, naming conventions, encoding, permissions, logging, security, line continuation, efficiency tricks, parallel execution, and integration with tools like shellcheck—to help developers write readable, maintainable, and performant scripts.
Code Style Guidelines
Due to work requirements, the author revisited shell scripting and found many scripts hard to read and maintain. To address this, a set of best‑practice guidelines is presented.
Shebang
The shebang ("#!") on the first line specifies the interpreter when none is given. A recommended form is: #!/usr/bin/env bash This approach improves portability.
Comments
Comments are essential in shell scripts because many one‑liner commands are not self‑explanatory. A good comment block should include:
Shebang
Script parameters
Purpose of the script
Usage notes
Author, date, license information
Function descriptions
Complex one‑liner explanations
Parameter Standards
Validate the number and format of parameters and provide clear feedback to the user.
Variables and Magic Numbers
Define important environment variables at the top of the script and avoid hard‑coded magic numbers; use named variables instead.
Indentation Rules
Use consistent indentation (soft tabs with 2 or 4 spaces or hard tabs) and avoid placing keywords like then or do on separate lines.
Naming Standards
File names should end with .sh.
Variable names must be meaningful and correctly spelled.
Use lowercase letters and underscores for shell variables.
Encoding Consistency
Prefer UTF‑8 without BOM. When editing on Windows, ensure the file is saved as UTF‑8 without BOM to avoid stray characters on Linux.
Permission
Remember to set executable permission (e.g., chmod +x script.sh) so the script can be run directly.
Logging and Echo
Provide informative logs and real‑time echo output for user‑facing scripts. Use ANSI/VT100 sequences for colors or effects if desired.
Password Removal
Never hard‑code passwords in scripts; keep them out of version control.
Line Continuation
For long command lines, use a backslash followed by a space to split lines for readability.
Encoding Details
Write concise code: prefer a single command over multiple commands when possible, which improves readability and performance.
Use Double Quotes
Enclose variable expansions in double quotes to prevent word splitting and globbing.
Main Function Trick
Encapsulate script logic inside a main() function and call it at the end to improve structure.
Scope Consideration
Variables are global by default; use local or readonly inside functions to limit scope.
Function Return Values
Functions return integer status codes; to output strings, use echo or printf.
Indirect Reference
Use the ${!var} syntax for simple indirect variable reference; avoid eval when possible.
Heredocs
Use heredocs (< Path Discovery Obtain the script's directory reliably with $(cd "$(dirname "$0")" && pwd) rather than relying on pwd alone. Code Conciseness Prefer fewer commands; for example, use sed -i 's/.../.../' file instead of multiple find ‑ sed pipelines. Parallel Execution Use & and wait or xargs -P to run commands in parallel, but limit concurrency to avoid overload. New Syntax Define functions with func() { … } instead of func { … } . Prefer [[ … ]] over [ … ] . Use $(command) instead of backticks. Prefer printf over echo for complex output. Other Tips Prefer absolute paths; if using relative paths, prefix with ./ . Prefer Bash parameter expansion over external tools like awk or sed when possible. Write simple conditionals on a single line using && and || . Namespace exported variables to avoid conflicts. Use trap to handle termination signals. Create 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 loops. Static Analysis with shellcheck Integrate the open‑source shellcheck tool into CI pipelines (e.g., Travis CI) to automatically detect common scripting issues and improve code quality.
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.
