Shell
Bash — scripting that does not bite back
Write Bash scripts that fail loudly, quote safely, and clean up after themselves: strict mode, quoting, parameter expansion, tests, loops, functions, arrays, traps, and the five bugs that bite everyone.
Docs-checkedbashscriptingshellparameter-expansionquoting
Quick reference — reach for these first
Strict mode
set -euo pipefailAbort on any error, unset variable, or failed command inside a pipe. First line after the shebang.Always quote
cp -- "$SRC" "$DST"Double-quote every expansion so spaces and glob chars in values are not re-split or expanded.Default value
name="${NAME:-anonymous}"Use a fallback when the variable is unset or empty — survives set -u.Capture output
today="$(date +%F)"Command substitution with $(...): nests cleanly, trims trailing newlines. Never use backticks.Clean up on exit
trap 'rm -f "$tmp"' EXITRun cleanup on every exit path — normal return, error, or Ctrl-C.Anatomy of a script that does not bite back
Text equivalent: A left-to-right flow of five stages. Stage one: shebang, hash-bang env bash. Stage two: set -euo pipefail, abort on error, unset var, pipe failure. Stage three: validate the arguments and exit with a code if they are wrong. Stage four, highlighted in accent: trap cleanup on EXIT so temp files are removed on any exit path. Stage five: do the work, then exit with a meaningful code. Arrows connect each stage to the next.
Common tasks
Task · Command · What to check
| Task | Command | What to check |
|---|---|---|
| Start every script with a strict-mode header | #!/usr/bin/env bash then set -euo pipefail | A deliberate `false` on its own line aborts the script immediately. |
| Double-quote every variable expansion | rm -- "$FILE" | A value with spaces stays one argument: `FILE='a b'` deletes one file, not two. |
| Provide a default for a maybe-unset var | name="${NAME:-anonymous}" | Unset NAME yields `anonymous` instead of a `-u` abort. |
| Strip a known suffix from a value | base="${FILE%.txt}" | `FILE=report.txt` gives `base=report`. |
| Get the length of a string | len="${#TOKEN}" | `TOKEN=abcd` gives `len=4`. |
| Capture command output into a variable | today="$(date +%F)" | `echo "$today"` prints the date with no trailing newline. |
| Prefer [[ ]] over [ ] for tests | [[ -f "$f" && -r "$f" ]] | Works even when $f is empty; `&&`, `||`, and `=~` are usable inside. |
| Loop over arguments without splitting | for a in "$@"; do echo "$a"; done | An argument containing spaces prints on a single line. |
| Scope variables inside functions | greet(){ local who="$1"; echo "hi $who"; } | A global named `who` is unchanged after calling greet. |
| Build and measure an array | files=( *.log ); echo "${#files[@]}" | Prints the element count; `"${files[@]}"` expands each element as one word. |
| Remove temp files on any exit | tmp="$(mktemp)"; trap 'rm -f "$tmp"' EXIT | After the script ends (even via Ctrl-C) the temp file is gone. |
| Feed multi-line input with a here-doc | cat <<'EOF' > out.txt ... EOF | A quoted `'EOF'` delimiter writes `$VAR` literally, with no expansion. |
A small safe script: strict mode, arg validation, trap cleanup, meaningful exit codes
problem->verify
1
Write the script. Strict mode first, validate the single argument, create a temp file guarded by a trap, do the work, then exit 0.
#!/usr/bin/env bash
set -euo pipefail
if [[ $# -ne 1 ]]; then
echo "usage: ${0##*/} SOURCE_DIR" >&2
exit 2
fi
SRC="$1"
[[ -d "$SRC" ]] || { echo "not a directory: $SRC" >&2; exit 3; }
tmp="$(mktemp)"
trap 'rm -f "$tmp"' EXIT # cleanup on every exit path
find "$SRC" -maxdepth 1 -type f > "$tmp"
count="$(wc -l < "$tmp" | tr -d ' ')"
echo "files in ${SRC}: ${count}"
exit 02
Make it executable.
chmod +x backup.sh
# (no output; file is now runnable)3
Run with no argument — validation fires before any work.
./backup.sh; echo "exit=$?"
# usage: backup.sh SOURCE_DIR
# exit=24
Run against a path that is not a directory — the second guard returns a distinct code.
./backup.sh /no/such/dir; echo "exit=$?"
# not a directory: /no/such/dir
# exit=35
Run against a real directory — work runs, temp file is auto-removed by the trap, exit is 0.
./backup.sh "$PWD"; echo "exit=$?"
# files in /path/to/dir: 6
# exit=0Troubleshooting — symptom → first check → next check
| Symptom | First check | Establishes | Next check |
|---|---|---|---|
| [: =: unary operator expected | Run `bash -x script.sh` and watch the test expand to `[ = foo ]`. | An unquoted empty variable collapsed the test — `[ $x = foo ]` with x unset becomes `[ = foo ]`. | Quote the operand and prefer the keyword form: `[[ "$x" = foo ]]`, which tolerates empty values. |
| A filename with spaces splits into many args, or `*` expands unexpectedly | Compare `echo "$var"` with `echo $var` — is the expansion quoted? | Unquoted `$var` undergoes word-splitting on IFS and then pathname (glob) expansion. | Wrap every expansion in double quotes; use `"$@"` (never bare `$@`) for argument lists. |
| "command not found" only inside the script, though it works in your shell | Add `echo "$PATH"` near the top and compare to your interactive PATH. | Cron and other non-interactive shells get a minimal PATH, and aliases/shell functions from your rc files are not loaded. | Call tools by absolute path, or set PATH explicitly at the top; replace aliases with real commands. |
| Script keeps running after a failed step and still reports success | Grep the file for `set -euo pipefail`. | Without `-e` a failing command is ignored; without `-o pipefail` a failure mid-pipe is masked by the last command's status. | Add `set -euo pipefail`; for a command allowed to fail, write `cmd || true` explicitly. |
| $'\r': command not found, or odd parse errors on clean-looking lines | Run `cat -A script.sh` — trailing `^M` marks CRLF line endings. | The file was saved with Windows CRLF endings, so each line ends in a stray carriage return. | Convert to LF (DESTRUCTIVE — rewrites the file in place): `sed -i 's/\r$//' script.sh` or `dos2unix script.sh`; set your editor to LF. |