Lesson 10 of 18Your tools
Shell Scripting Without Tears
Write bash scripts that fail loudly instead of silently: strict mode, quoting, arguments, functions, cleanup with trap, and when to switch to Python.
Every team has a few shell scripts holding things together: bootstrap.sh that sets up a fresh clone, deploy.sh that CI runs, a cron job that backs up the database. They are usually written in a hurry and they usually work, until the day one command fails halfway and the script carries on regardless, deploying a half-built app or "backing up" an empty file for three months. Bash's defaults are tuned for typing at a prompt, not for automation. This lesson is about changing those defaults and writing scripts that stop at the first problem, clean up after themselves, and tell the next person how to use them.
It builds on Shell Power Tools, especially quoting and exit codes. If those are hazy, reread them first.
Your first script
A script is a text file of commands with a first line that says which program should run it:
#!/usr/bin/env bashecho "Hello from $(hostname), it is $(date +%H:%M)"The first line is the shebang. #!/usr/bin/env bash means "find bash on the PATH and run this file with it". That is more portable than #!/bin/bash, because bash lives in different places on different systems. Then make the file executable and run it:
chmod +x hello.sh # add the execute permission (once)./hello.sh # run it; the shebang picks bashbash hello.sh # or name the interpreter yourself; no chmod neededThe ./ matters. The current folder is not on your PATH (for security), so hello.sh alone gives "command not found". Also note that sh hello.sh is not the same as bash hello.sh. On Ubuntu, sh is dash, a smaller shell that rejects bash features like [[ ]]. If your script uses bash, run it with bash.
Strict mode: fail loudly
By default, bash runs every line even if the previous one failed. Put this right under the shebang of every script:
set -euo pipefailEach letter stops a different silent failure:
-e(errexit): exit as soon as a command fails. Without it,cd buildcan fail and the next line,rm -rf *, runs in the wrong folder.-u(nounset): treat an unset variable as an error. Without it, a typo inrm -rf "$BUILD_DRI/"expands torm -rf "/".-o pipefail: a pipeline fails if any stage fails. Without it,curl https://broken | jq .reports the exit code ofjqonly, which succeeds on empty input.
set -e is a safety net with holes, and seniors know where they are. Commands in an if condition, or on the left of && or ||, are allowed to fail (that is how you test things). Here are the traps that catch people:
set -euo pipefail# 1. local hides the exit code of $(...), so a failure is ignored.f() { local out=$(false) # does NOT exit: local itself succeeded local out2 out2=$(false) # exits here, as you wanted}# 2. ((count++)) when count is 0 "returns" 0, which counts as failure.count=0((count++)) # bash 4.1+ exits here; macOS bash 3.2 does notcount=$((count + 1)) # always safe# 3. With pipefail, head closing the pipe early can kill the script.seq 1 100000 | head -n 1 # exits with 141 (SIGPIPE) when the writer is still busy# 4. Unset optional variables need a default under -u.echo "${DEBUG:-false}" # prints false instead of crashingTrap 2 is especially nasty: your script works on your Mac and dies in Linux CI. Trap 3 is real too: head stops reading after one line, the writer gets a "broken pipe" signal, and its exit code becomes 128 + 13 = 141. If you need the first line of a big stream under pipefail, add || true to that pipeline or restructure it.
set -euo pipefail and a function containing local token=$(get_token). get_token fails. What happens?Variables, quoting and expansions
Assign with no spaces around =. name = "Ada" runs a command called name with two arguments.
name="Ada" # no spaces around =greeting="Hello, $name" # double quotes expand variablestoday=$(date +%Y-%m-%d) # command substitution: capture outputtotal=$(( 7 * 6 )) # arithmetic: 42 (integers only)echo "${name}_backup" # braces mark where the name endsecho "${PORT:-8000}" # use 8000 if PORT is unset or emptyfile="report.tar.gz"echo "${file%.gz}" # report.tar (remove shortest match from the end)echo "${file%%.*}" # report (remove longest match from the end)The rule from Shell Power Tools applies with full force in scripts: quote every expansion. "$file", "$(command)", "$@". Unquoted, bash splits the value on spaces and expands any * in it. The only common places quotes are not needed are inside [[ ]] and $(( )), and quoting there does no harm.
Arguments and a usage message
Your script receives its arguments as positional parameters:
| Name | Holds |
|---|---|
$0 | The script's own name |
$1, $2 ... | The first, second ... argument |
$# | How many arguments there are |
"$@" | All arguments, each kept as its own word |
"$*" | All arguments joined into one string |
$? | Exit code of the last command |
"$@" is almost always what you want. It passes arguments through exactly as the caller gave them, spaces and all.
What does this print in bash?
set -- "hello world" two # pretend the script was called with these 2 arguments for a in $*; do echo "[$a]"; done
A real script parses flags, validates what it got, and prints a usage message when something is wrong. This pattern handles short and long flags without any library:
#!/usr/bin/env bashset -euo pipefailusage() { echo "Usage: $(basename "$0") [-n|--dry-run] [-e|--env ENV] TARGET" >&2 exit 2}dry_run=falseenv="staging"while [[ $# -gt 0 ]]; do case "$1" in -n|--dry-run) dry_run=true; shift ;; -e|--env) [[ $# -ge 2 ]] || usage; env="$2"; shift 2 ;; -h|--help) usage ;; --) shift; break ;; -*) echo "Unknown option: $1" >&2; usage ;; *) break ;; esacdone[[ $# -eq 1 ]] || usagetarget="$1"echo "target=$target env=$env dry_run=$dry_run"shift drops $1 and moves every argument down by one, so the loop always looks at $1. Running ./deploy.sh -n --env prod api prints target=api env=prod dry_run=true. Running it with no target prints the usage line to stderr (>&2) and exits with 2, the conventional code for "you used me wrong". Error messages go to stderr so they do not pollute output that someone pipes into another command.
Match each expansion to what it gives you.
Conditions, loops and functions
[[ ]] is bash's test command. The common checks:
if [[ -f "$config" ]]; then echo "file exists"; fiif [[ -d "$dir" ]]; then echo "directory exists"; fiif [[ -z "$token" ]]; then echo "token is empty" >&2; exit 1; fiif [[ "$env" == "prod" && "$dry_run" == false ]]; then echo "really deploying"; fiif [[ "$version" =~ ^v[0-9]+\.[0-9]+$ ]]; then echo "looks like v1.2"; fiif ! command -v jq >/dev/null 2>&1; then echo "jq is not installed" >&2; fiAny command can be a condition: if runs it and checks for exit code 0. That is why if grep -q "TODO" file; then works, and why command -v tool is the standard way to check a tool is installed (it is built into the shell and works everywhere, unlike which).
Looping over files safely means letting the shell glob, not parsing ls:
for f in data/*.csv; do [[ -e "$f" ]] || continue # no matches: bash leaves the literal pattern echo "processing $f"done# Recursive and safe with any filename:find data -name '*.csv' -print0 | while IFS= read -r -d '' f; do echo "processing $f"doneFunctions group steps and take arguments the same way scripts do ($1, "$@"). Mark their variables local, or they leak into the whole script:
log() { printf '==> %s\n' "$*"; }die() { printf 'error: %s\n' "$*" >&2; exit 1; }backup_db() { local db="$1" dest="$2" [[ -d "$dest" ]] || die "no such directory: $dest" log "Backing up $db to $dest"}Cleanup with trap, temp files and heredocs
Scripts often need a scratch directory. Create it with mktemp (never a fixed name like /tmp/build, which two runs can share), and register cleanup with trap ... EXIT, which runs however the script ends: success, failure under -e, or Ctrl+C.
#!/usr/bin/env bashset -euo pipefailtmp="$(mktemp -d)"cleanup() { rm -rf "$tmp"; }trap cleanup EXITcurl -fsS https://api.example.com/stats > "$tmp/stats.json"jq -r '.daily[] | "\(.date),\(.users)"' "$tmp/stats.json" > "$tmp/stats.csv"cat > report.md <<EOF# Weekly reportGenerated $(date +%Y-%m-%d) from $(wc -l < "$tmp/stats.csv" | tr -d ' ') days of data.EOFmktemp -d creates a uniquely named directory, so two runs never collide.
The <<EOF ... EOF block is a heredoc: multi-line text fed to a command's input. Variables and $(...) expand inside it. Quote the marker, <<'EOF', and the text is kept literally, which is what you want when writing out a script or config that contains $ signs.
A real one: bootstrap.sh
Here is the script many repos have at the root, so a new hire can go from git clone to a running app in one command. It checks for tools before doing anything, installs dependencies, and never overwrites an existing .env:
#!/usr/bin/env bash# Set up a fresh clone: check tools, install deps, create .env.set -euo pipefailcd "$(dirname "$0")" # run from the repo root, wherever it was called fromlog() { printf '==> %s\n' "$*"; }die() { printf 'error: %s\n' "$*" >&2; exit 1; }require() { local tool="$1" hint="$2" command -v "$tool" >/dev/null 2>&1 || die "$tool is not installed. $hint"}require git "Install Git from git-scm.com."require uv "Install uv: https://docs.astral.sh/uv/"require node "Install Node.js 22 or later."log "Installing Python dependencies"uv synclog "Installing JavaScript dependencies"npm ciif [[ ! -f .env ]]; then cp .env.example .env log "Created .env from .env.example. Fill in the secrets."else log ".env already exists, leaving it alone"filog "Done. Run: uv run pytest"Notice the shape: it is idempotent, meaning running it twice is safe. The second run reinstalls nothing harmful and leaves your .env alone. Scripts that people run again and again, on laptops and in CI, should always be safe to repeat.
Put the parts of a well-structured script in order, top to bottom.
- Tap the steps below in the right order.
Lint it, and know when to stop
Install ShellCheck (brew install shellcheck, apt install shellcheck, or the VS Code extension) and run it on every script, ideally in CI. It catches the bugs in this lesson automatically: unquoted variables (SC2086), local masking exit codes (SC2155), cd without handling failure, and dozens more, each with a wiki page explaining why.
shellcheck deploy.sh bootstrap.shThen know when bash is the wrong tool. A good rule of thumb: once a script passes about 50 lines, needs real data structures (lists of records, JSON beyond a jq one-liner), error handling more subtle than "stop", or tests, rewrite it in Python. Bash is excellent glue for running other programs. It is poor at everything else. Here is the flag parsing from deploy.sh in Python, with validation and --help for free:
Press Run (⌘ Enter) to see what happens.Python gives the same exit code 2 for bad usage that the bash version chose by hand. That convention is not a coincidence.
set -euo pipefail and then generate_report | head -n 5. It passes locally but CI sometimes fails with exit code 141. Why?- shebang
- The first line, like
#!/usr/bin/env bash, that tells the system which interpreter runs the file. - strict mode
set -euo pipefail: exit on errors, error on unset variables, and fail a pipeline if any stage fails.- positional parameters
$1,$2and so on, plus$#(count) and"$@"(all of them, each intact).- trap
- Runs a command when the shell receives a signal or exits.
trap cleanup EXITis the standard cleanup hook. - heredoc
- A
<<EOFblock that feeds multi-line text to a command. Quote the marker to stop expansion. - idempotent
- Safe to run more than once with the same result, such as a setup script that skips work already done.
- ShellCheck
- A linter for shell scripts that catches quoting bugs, masked exit codes and other common mistakes.