Skip to content

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.

22 min read0/5 questions

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:

hello.sh
#!/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 needed

The ./ 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 pipefail

Each letter stops a different silent failure:

  • -e (errexit): exit as soon as a command fails. Without it, cd build can 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 in rm -rf "$BUILD_DRI/" expands to rm -rf "/".
  • -o pipefail: a pipeline fails if any stage fails. Without it, curl https://broken | jq . reports the exit code of jq only, 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:

strict-mode-gotchas.sh
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 crashing

Trap 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.

Quick check
A script has set -euo pipefail and a function containing local token=$(get_token). get_token fails. What happens?
Need a nudge? A hint rules out a wrong answer.

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:

NameHolds
$0The 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.

Predict the outputShell

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
Need a nudge? Hints walk you through it.

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:

deploy.sh
#!/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 the pairs0/6 matched

Match each expansion to what it gives you.

Choose an item, then its match on the other side.

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; fi

Any 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"done

Functions 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.

build-report.sh
#!/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.EOF
trap EXIT when a command fails
ScriptbashTemp dirmktemp -dtrap cleanup EXITcurl fails (exit 22)run cleanuprm -rfexit 22

mktemp -d creates a uniquely named directory, so two runs never collide.

1/6

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:

bootstrap.sh
#!/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 it in order6 steps

Put the parts of a well-structured script in order, top to bottom.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

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.sh

Then 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:

Python
import argparseimport shutil parser = argparse.ArgumentParser(prog="deploy")parser.add_argument("target")parser.add_argument("-n", "--dry-run", action="store_true")parser.add_argument("-e", "--env", default="staging", choices=["staging", "prod"]) # On your machine this would be parser.parse_args() reading sys.argv.args = parser.parse_args(["-n", "--env", "prod", "api"])print(args)print(f"target={args.target} env={args.env} dry_run={args.dry_run}") # shutil.which is Python's command -v. In the browser there is no PATH# with these tools, so you will see None here.for tool in ["git", "uv", "node"]: print(f"{tool:5} found at: {shutil.which(tool)}") try: parser.parse_args(["--env", "qa", "api"])except SystemExit as e: print("bad --env exits with code", e.code)
Output
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.

Quick check
A CI step runs set -euo pipefail and then generate_report | head -n 5. It passes locally but CI sometimes fails with exit code 141. Why?
Need a nudge? A hint rules out a wrong answer.
Key terms
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, $2 and so on, plus $# (count) and "$@" (all of them, each intact).
trap
Runs a command when the shell receives a signal or exits. trap cleanup EXIT is the standard cleanup hook.
heredoc
A <<EOF block 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.