Reading — step 1 of 5
Learn
~1 min readRobust Scripting
Bash by default is forgiving in ways that hide bugs. Always start scripts with strict mode:
#!/bin/bash
set -euo pipefail
-e— exit on any non-zero command (instead of plowing ahead)-u— error on unset variables (catches typos)-o pipefail— pipeline fails if any stage fails (not just the last)
With these, cat missing.txt | grep foo actually fails the script. Without, you'd silently continue.
ALWAYS quote your variables unless you have a specific reason not to:
# WRONG — breaks on filenames with spaces
for f in $files; do
rm $f
done
# RIGHT — quoted, preserves spaces
for f in "${files[@]}"; do
rm "$f"
done
Word splitting and glob expansion happen on UNQUOTED variables. Quoting is rarely wrong; not quoting is usually wrong.
Test commands — [[ ... ]] is the modern Bash conditional (vs the older [ ... ]):
[[ "$x" == "hello" ]] # string equality
[[ "$x" =~ ^[0-9]+$ ]] # regex match
[[ -f "$path" ]] # file exists
[[ -z "$s" ]] # string empty
[[ "$a" -gt "$b" ]] # numeric (or use (( )) )
[[ ... ]] doesn't word-split, doesn't glob — safer than [ ... ].
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…