Bash Patterns Real Scripts Use
In this article
The most useful bash patterns in real scripts are defensive error handling, strict mode, and parameter expansion for safe string manipulation. These patterns prevent silent failures, handle unexpected inputs, and make scripts robust enough for production use.
Why Bash Scripting Still Matters
Bash remains the default shell on virtually all Linux distributions and macOS, and it is the glue that ties together system administration, CI/CD pipelines, and developer tooling. Even with modern alternatives like Python or Go, bash is often the fastest way to automate file operations, process text, and orchestrate other commands. Real-world scripts—from startup deployment scripts to enterprise configuration management—rely on a core set of patterns that have proven themselves over decades.
Strict Mode: The Foundation
Every robust bash script starts with a set of options that change the shell's default error tolerance. The most common combination is:
set -e— exit immediately if any command returns a non-zero statusset -u— treat unset variables as an error and exitset -o pipefail— make a pipeline return the status of the last command that failed
These three lines prevent the classic problems of scripts continuing after a failure and using empty variables. However, set -e can be surprising: it does not trigger inside command substitutions or in conditions like if statements. A common refinement is to use set -E to make traps inherit, and to explicitly handle commands where failure is acceptable with || true.
Error Handling and Traps
Real scripts do not just exit on error—they clean up after themselves. The trap command is the standard way to run cleanup code when the script exits, whether normally or due to an error. A typical pattern is:
cleanup() { rm -rf "$TMPDIR" }
trap cleanup EXIT
TMPDIR=$(mktemp -d)Using trap ... EXIT ensures the temp directory is removed even if the script crashes. For debugging, trap 'echo "Error at line $LINENO"' ERR prints the line number where a command failed. This is invaluable when a script runs unattended in a cron job.
Parameter Expansion for Safe Variable Handling
Bash's parameter expansion is more powerful than most users realize. It provides built-in defaults, error messages, and string manipulation without calling external tools like sed or awk. The most useful forms are:
${var:-default}— usedefaultifvaris unset or empty${var:=default}— assigndefaulttovarif it is unset or empty${var:?error message}— exit with an error ifvaris unset or empty${var#pattern}and${var%pattern}— remove shortest match from the beginning or end${var##pattern}and${var%%pattern}— remove longest match${var/old/new}— replace first occurrence
For example, to extract a filename from a full path, ${path##*/} is faster and safer than piping to basename. To remove an extension, ${filename%.*} works without spawning a subprocess.
Arrays and Loops
Bash arrays are underused but essential for handling lists of items without relying on word splitting. A common pattern is to read a list of files into an array and iterate over it:
files=(*.txt)
for f in "${files[@]}"; do
echo "Processing $f"
doneThe quoting "${files[@]}" is critical—it preserves spaces in filenames. Without quotes, filenames with spaces would be split into multiple words. Another useful pattern is to use mapfile (or readarray) to read lines from a file into an array:
mapfile -t lines < "$config_file"This avoids the pitfalls of for line in $(cat file), which breaks on spaces and glob characters.
Robust Command Substitution and Quoting
Command substitution is everywhere in bash, but it has subtle traps. Always quote the result: result="$(command)" preserves trailing newlines and prevents word splitting. For commands that might fail, combine with set -e carefully—if the command substitution is part of an assignment, a failure will not exit the script unless you check $? explicitly. A safer pattern is:
if output=$(command); then
echo "Success: $output"
else
echo "Failed"
fiThis captures the output and tests the exit status in one step, avoiding a race condition where the status could be overwritten by another command.
Common Pitfalls and Misconceptions
One of the most common mistakes is using if [ $var = "yes" ] without quoting $var. If var is empty, the test becomes [ = "yes" ] which is a syntax error. Always quote: if [ "$var" = "yes" ]. Another pitfall is relying on set -e to catch errors in pipelines—without set -o pipefail, a pipeline like cmd1 | cmd2 returns the status of cmd2 only, even if cmd1 fails.
A misconception is that [[ ]] and [ ] are interchangeable. The double-bracket [[ ]] is a bash keyword that supports pattern matching and does not require quoting variables, while [ ] is a command that follows POSIX rules. For portability to POSIX shells, use [ ]; for bash-specific scripts, [[ ]] is safer and more readable.
Frequently Asked Questions
Why does my script continue after a command fails?
This happens when you do not have set -e enabled, or when the failing command is part of a condition, a pipeline without pipefail, or a command substitution in an assignment. Check your shebang line and add set -euo pipefail at the top. Remember that set -e is disabled in if conditions, so you must handle those explicitly.
How do I safely handle filenames with spaces?
Always quote your variables: "$file". When iterating over files, use an array: files=(*.txt) and loop with for f in "${files[@]}". Avoid parsing ls output—use globs or find -print0 with while IFS= read -r -d '' for null-delimited output.
What does ${var:-default} do exactly?
It expands to default if var is unset or empty; otherwise it expands to the value of var. This is useful for optional arguments: name="${1:-World}" sets name to the first argument or "World" if none is provided.
Is it better to use [[ ]] or [ ]?
For bash scripts, use [[ ]] because it is more robust: no word splitting, supports regex with =~, and allows pattern matching. If you need POSIX compatibility (e.g., for sh), use [ ] with proper quoting.
How can I debug my bash script?
Run it with bash -x script.sh to trace each command. You can also add set -x inside the script to turn on tracing, and set +x to turn it off. For more targeted debugging, use trap 'echo "$BASH_COMMAND failed at line $LINENO"' ERR.
What is the best way to read a file line by line?
Use while IFS= read -r line; do ...; done < file. The -r prevents backslash escaping, and IFS= preserves leading/trailing whitespace. This is safer than for line in $(cat file) because it handles spaces and special characters correctly.