← All cheatsheets

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 modeset -euo pipefailAbort on any error, unset variable, or failed command inside a pipe. First line after the shebang.
Always quotecp -- "$SRC" "$DST"Double-quote every expansion so spaces and glob chars in values are not re-split or expanded.
Default valuename="${NAME:-anonymous}"Use a fallback when the variable is unset or empty — survives set -u.
Capture outputtoday="$(date +%F)"Command substitution with $(...): nests cleanly, trims trailing newlines. Never use backticks.
Clean up on exittrap 'rm -f "$tmp"' EXITRun cleanup on every exit path — normal return, error, or Ctrl-C.

Anatomy of a script that does not bite back

Anatomy of a safe Bash scriptFive stages left to right: shebang, strict mode, validate args and exit on bad input, trap cleanup on EXIT (accent), then do work and exit with a meaningful code.#!/usr/bin/envbashset -euopipefail[[ $# -eq 1 ]]|| exit 2trap 'rm -f"$tmp"' EXITdo workexit Nshebangstrict modevalidatecleanup hookrun + statusQuote every "$expansion" at every stage; exit codes 2/3/N tell the caller what went wrong.

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

TaskCommandWhat to check
Start every script with a strict-mode header#!/usr/bin/env bash then set -euo pipefailA deliberate `false` on its own line aborts the script immediately.
Double-quote every variable expansionrm -- "$FILE"A value with spaces stays one argument: `FILE='a b'` deletes one file, not two.
Provide a default for a maybe-unset varname="${NAME:-anonymous}"Unset NAME yields `anonymous` instead of a `-u` abort.
Strip a known suffix from a valuebase="${FILE%.txt}"`FILE=report.txt` gives `base=report`.
Get the length of a stringlen="${#TOKEN}"`TOKEN=abcd` gives `len=4`.
Capture command output into a variabletoday="$(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 splittingfor a in "$@"; do echo "$a"; doneAn argument containing spaces prints on a single line.
Scope variables inside functionsgreet(){ local who="$1"; echo "hi $who"; }A global named `who` is unchanged after calling greet.
Build and measure an arrayfiles=( *.log ); echo "${#files[@]}"Prints the element count; `"${files[@]}"` expands each element as one word.
Remove temp files on any exittmp="$(mktemp)"; trap 'rm -f "$tmp"' EXITAfter the script ends (even via Ctrl-C) the temp file is gone.
Feed multi-line input with a here-doccat <<'EOF' > out.txt ... EOFA 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 0
2
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=2
4
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=3
5
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=0

Troubleshooting — symptom → first check → next check

SymptomFirst checkEstablishesNext check
[: =: unary operator expectedRun `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 unexpectedlyCompare `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 shellAdd `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 successGrep 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 linesRun `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.