Boost Bash Script Reliability: Essential Safety Practices and Advanced Tips
This guide presents practical Bash scripting techniques—including safety flags, function design, variable annotations, modern command substitution, double‑bracket tests, string manipulation, process substitution, debugging tools, and when to avoid Bash—to help you write more robust and maintainable shell scripts.
Script Safety
Start every Bash script with a shebang and strict error handling:
#!/usr/bin/env bash
set -o nounset # treat unset variables as an error
set -o errexit # exit on any command failureNote that commands like mkdir -p or rm -f intentionally suppress errors.
Functions
Encapsulate reusable logic in functions. Example of extracting comment lines:
ExtractBashComments() {
egrep "^#"
}
cat myscript.sh | ExtractBashComments | wc -l
comments=$(ExtractBashComments < myscript.sh)Other useful patterns:
SumLines() {
local sum=0
while read -r line; do
sum=$((sum + line))
done
echo "$sum"
}
log() {
local prefix="[$(date +'%Y/%m/%d %H:%M:%S')]: "
echo "${prefix}$@" >&2
}
log "INFO" "a message"Place only global constants and the final call to a main -like function at the top level.
Variable Annotations
Use local for function‑scoped variables and readonly for constants:
# Default value can be overridden by an environment variable
readonly DEFAULT_VAL=${DEFAULT_VAL:-7}
myfunc() {
local some_var=${DEFAULT_VAL}
# …
}Attempting to modify a readonly variable triggers an error:
x=5
readonly x
x=7 # error: cannot assign to readonly variableCommand Substitution
Prefer $() over backticks for readability and nesting:
# old style (hard to read)
echo "A-`echo B-\`echo C-\\\`echo D\\\``"
# modern style
echo "A-$(echo B-$(echo C-$(echo D)))"Conditional Expressions
Use double brackets [[ … ]] for richer syntax, pattern matching and regular expressions:
[[ "$t" == abc* ]] # glob pattern, true if $t starts with "abc"
[[ "$t" =~ [abc]+[123]+ ]] # regex matchPatterns must not be quoted (Bash 3.2+). Variables can hold patterns with spaces:
r="a b+"
[[ "a bbb" =~ $r ]] # truePattern Matching in case
Double brackets simplify case statements as well:
case $t in
abc*) echo "matched abc*" ;;
*) echo "no match" ;;
esacString Operations
Common parameter‑expansion techniques:
Length: len=${#var} Slicing: sub=${var:6} or sub=${var:6:5} From end: sub=${var: -8} (note the space before -)
Pattern substitution: ${var/pattern/repl} (single) and ${var//pattern/repl} (global)
Delete prefix/suffix: ${var#prefix}, ${var##prefix}, ${var%suffix},
${var%%suffix}Avoid Temporary Files
Process substitution treats command output as a file descriptor:
diff <(wget -qO - "$url1") <(wget -qO - "$url2")Here‑documents feed multiline strings to a command:
command <<MARKER
Line 1 with ${var}
$(date)
MARKERQuote the delimiter to suppress variable expansion when not needed:
command <<'MARKER'
Literal $var and $(cmd) are not expanded.
MARKERBuilt‑in Variables
Prefer "$@" over "$*" for handling positional parameters that may contain spaces. Always quote "$@" when expanding.
Debugging
Syntax check without execution: bash -n script.sh Trace each command as it is read: bash -v script.sh Execute with execution tracing (shows each command and its arguments): bash -x script.sh Alternatively, enable tracing at the script start with set -o verbose and set -o xtrace.
When Not to Use Bash
Scripts exceed a few hundred lines and become hard to maintain.
Complex data structures (e.g., associative arrays, trees) are required.
Escaping rules become overly intricate.
Heavy string manipulation dominates the logic.
Little interaction with external programs or pipelines.
Performance is critical.
In such cases consider a higher‑level language such as Python or Ruby.
References
Advanced Bash‑Scripting Guide: http://tldp.org/LDP/abs/html/
Bash Reference Manual
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.
ITPUB
Official ITPUB account sharing technical insights, community news, and exciting events.
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.
