Platform Engineering · Lesson 03

The Shell Without Surprises: Quoting, Pipes, Redirects, Globs, Variables, and Exit Codes

Before a command runs, the shell rewrites the line you typed: it expands variables, splits words, matches file names against wildcards, and sets up redirects and pipes. Most beginner surprises, and many production accidents, come from that rewriting. This lesson follows one line through the shell, step by step: variables, quoting, globs, redirects, pipes, and the exit code that tells the next command whether it worked. Two failures show why it matters: an unquoted file name with a space in it, and a pipeline whose failure nobody saw.

Difficulty: Beginner · Know this first: Lesson 02

What you will learn

By the end of this lesson you can work at four levels:

This page teaches it with a plain-language analogy, an animated diagram with normal and failure scenarios, a simulator, a quiz, basic, intermediate, advanced, and master checks, the expert detail ("Go deeper"), a production incident, a hands-on lab with commands and their output, and a production design exercise.

Run it as:

When it breaks, I check

One thing to remember

Where the time goes

This bar adds up seconds for one backup script to finish and report, and, when it fails silently, until someone finds out. It is a worked example, not a measurement. The quoting and exit code hops decide whether a script does what it says.

Try it: does your script do what it says?

Pick how the variable is written, whether the script stops on errors, and how the pipeline reports failure.

1arguments cp receives for the file
successthe script says
trueand that is

Check yourself

Three questions. No score is saved anywhere — this is just you against the material.

Basic to master

Working in the shell grows in four levels: running commands, combining them, writing safe scripts, and reviewing others' scripts.

Basic — Run commands

At the basic level you can run a command and read what it says.

  • Commands, options, and arguments.
  • Variables, and double quotes around them.
  • The exit code in $? and what 0 means.

Where it breaks: file names with spaces, and errors you did not read.

Try it: Basic

You ran a command and want to know if it succeeded. What do you check?

Now do it: Run ls on a missing file and echo $?.

Intermediate — Combine them

At the intermediate level you build answers out of small tools.

  • Pipes, redirects, and 2>&1.
  • Globs, previewed with echo.
  • && and || for simple conditions.

Try it: Intermediate

grep ERROR app.log | wc -l prints 0, but you can see errors on screen. Why?

Now do it: Try grep -ic error app.log.

Advanced — Write safe scripts

At the advanced level your scripts fail loudly and never surprise you.

  • set -euo pipefail, quoted variables, and ${VAR:?} guards before destructive commands.
  • shellcheck on every script.
  • Clear exit codes and messages on standard error.

Try it: Advanced

Why write rm -rf "${BUILD_DIR:?}"/* instead of rm -rf "$BUILD_DIR"/*?

Now do it: Add :? guards to one of your scripts.

Master — Review and replace

At the master level you know when the shell is the wrong tool.

  • Reviewing others' scripts for quoting, globbing, and error handling.
  • Moving logic past a few dozen lines into Python or Go.
  • Testing scripts (bats) and running them in CI.

Trade-off: the shell is unbeatable for gluing tools together and fragile for logic; draw the line before the script grows its own data structures.

Try it: Master

A deploy script has grown to 600 lines of Bash with arrays and string parsing. What do you suggest?

Now do it: Run shellcheck on your longest script.

Go deeper

The order the shell processes a line in (Bash): brace expansion ({a,b}), tilde expansion (~), parameter and variable expansion ($X), command substitution ($(cmd)), arithmetic ($((1+2))), word splitting (unquoted results only), pathname expansion (globs, unquoted only), quote removal; redirections are set up just before the command runs.

#!/usr/bin/env bash
set -euo pipefail                      # stop on errors, unset variables, and pipeline failures
SRC="${1:?usage: backup.sh FILE}"      # required argument, with a message if missing
DEST="${BACKUP_DIR:-$HOME/backups}"    # default value if BACKUP_DIR is unset
mkdir -p -- "$DEST"
gzip -9 < "$SRC" > "$DEST/$(basename -- "$SRC").gz"
gzip -t "$DEST/$(basename -- "$SRC").gz"   # verify before saying it worked
echo "backed up $SRC" >&2

-- ends options, so a file name starting with a dash is not read as an option. shellcheck (from your package manager) finds unquoted variables and most of the traps in this lesson automatically.

One time it broke

This is a composite of a failure pattern that keeps repeating; the details are illustrative. The backup that was always green.

Timeline

  • Night 1The database export URL changes during a migration. The nightly job, curl -s "$URL" | gzip > /backups/db-$(date +%F).sql.gz, gets an error page, compresses it, and exits 0.
  • Nights 2-9The job stays green. Each backup is a few hundred bytes.
  • Day 10A table is dropped by mistake. Every backup since the migration contains the same error page.
  • Day 10Data is recovered from a replica's delayed copy, losing some hours of changes.

What changed after

set -euo pipefail and curl -fsS (fail on HTTP errors, quiet but show errors) in every job; a restore test after each backup; and an alert when a backup is much smaller than the previous one.

Try it yourself, from scratch

Everything here runs on any Linux machine: your own laptop, WSL on Windows (run wsl --install in PowerShell once), or a small cloud VM. The Python needs only Python 3 and its standard library; check that you have it with python3 --version.

Before you start: A Linux shell with Bash (WSL, Linux, or macOS; on macOS run bash first, since the default shell is zsh) and Python 3.

1. Linux commands

Type each one, read what it prints, and compare it with the note above it.

  1. Make a lab folder and a file whose name has a space, then see what the program receives with and without quotes. printf '[%s]\n' prints each argument it gets inside brackets.

    Reversible

    mkdir -p ~/labs/shell && cd ~/labs/shell
    SRC="May report.csv"
    printf 'id,total\n1,40\n' > "$SRC"
    printf '[%s]\n' $SRC
    printf '[%s]\n' "$SRC"

    Options: NAME=value sets a variable (no spaces around =); printf FORMAT ARGS repeats the format for each argument.

    Expect: Unquoted: [May] and [report.csv], two arguments. Quoted: [May report.csv], one argument. That split is what breaks cp $SRC backup/.

    Clean up: cd ~ && rm -rf ~/labs/shell.

  2. Single quotes against double quotes.

    Read-only

    echo 'single: $HOME'
    echo "double: $HOME"

    Expect: single: $HOME (nothing expanded), then double: /home/you (expanded, kept as one word; /root if you are root).

  3. Globs: the shell turns patterns into file names before the program runs.

    Reversible

    touch a.log b.log notes.txt
    echo *.log
    echo "*.log"
    echo *.xyz

    Options: touch creates empty files; * matches any characters in a name.

    Expect: a.log b.log (expanded), *.log (quoted, so left alone), and *.xyz (no match, so Bash passes the pattern unchanged).

    If it fails: Always echo a pattern before using it with rm: what echo prints is exactly what rm would delete.

  4. Standard output and standard error go to different places.

    Reversible

    ls "$SRC" nofile > out.txt 2> err.txt; echo "exit $?"
    cat out.txt
    cat err.txt

    Options: > sends standard output to a file (replacing it); 2> sends standard error; $? is the exit code of the last command.

    Expect: exit 2 (ls failed on one of the two names), out.txt holds May report.csv, and err.txt holds ls: cannot access 'nofile': No such file or directory.

  5. A pipeline's exit code, with and without pipefail. false always fails; true always succeeds.

    Read-only

    false | true; echo "without pipefail: $?"
    set -o pipefail; false | true; echo "with pipefail: $?"; set +o pipefail

    Options: set -o pipefail makes a pipeline fail if any command in it fails; set +o turns it off again.

    Expect: without pipefail: 0 (the failure of false is lost), then with pipefail: 1.

  6. Guards that stop a script before an empty variable does damage. Both run in a child shell, so your own shell is unaffected, and the dangerous command is only echoed.

    Read-only

    bash -c 'set -u; echo "value: $NOT_SET"'; echo "exit $?"
    bash -c 'D=""; echo rm -rf "${D:?D is empty, refusing}"/*'; echo "exit $?"

    Options: set -u makes an unset variable an error; ${D:?message} stops with the message if D is unset or empty.

    Expect: bash: line 1: NOT_SET: unbound variable, then a non-zero exit (127 in current Bash); bash: line 1: D: D is empty, refusing and a non-zero exit. Without the guard, "$D"/* would have become /*: every folder at the top of the filesystem.

  7. Clean up.

    Potentially destructive

    cd ~ && rm -rf ~/labs/shell
    ls ~/labs

    Expect: No error, and shell is no longer listed. This is a destructive command made safe by its exact, quoted path inside ~/labs.

2. Python: shell_words.py

This program imitates the part of the shell this lesson is about: it expands variables, splits unquoted values into words, keeps quoted text together, and matches globs against a folder listing, then prints the arguments the program would receive. It is a model for learning, not a full shell. Save it as shell_words.py, then run it.

# shell_words.py
import fnmatch
import re

ENV = {"SRC": "May report.csv", "HOME": "/home/asha", "EMPTY": ""}
FILES = ["May report.csv", "a.log", "b.log", "notes.txt"]          # the current folder

def var(line, i):                                   # $NAME, or NAME in braces, at i -> (value, next i)
    m = re.match(r"\$(\w+)|\$\{(\w+)\}", line[i:])
    return ENV.get(m.group(1) or m.group(2), ""), i + m.end()

def words(line):
    out, cur, have, glob = [], "", False, False
    def flush():
        nonlocal cur, have, glob
        if have:
            hits = sorted(f for f in FILES if fnmatch.fnmatchcase(f, cur)) if glob else []
            out.extend(hits or [cur])                 # no match: the pattern stays as it is
        cur, have, glob = "", False, False
    i = 0
    while i < len(line):
        c = line[i]
        if c == " ":
            flush(); i += 1
        elif c == "'":                              # single quotes: literal, no expansion
            j = line.index("'", i + 1); cur += line[i + 1:j]; have = True; i = j + 1
        elif c == '"':                              # double quotes: expand, never split or glob
            j = i + 1
            while line[j] != '"':
                if line[j] == "$":
                    v, j = var(line, j); cur += v
                else:
                    cur += line[j]; j += 1
            have = True; i = j + 1
        elif c == "$":                              # unquoted expansion: split on spaces
            v, i = var(line, i)
            for k, part in enumerate(v.split()):
                if k:
                    flush()
                cur += part; have = True
        else:
            glob = glob or c in "*?["
            cur += c; have = True; i += 1
    flush()
    return out

for line in ['cp $SRC backup/', 'cp "$SRC" backup/', "echo '$HOME' \"$HOME\"",
             'ls *.log "*.log" *.xyz', 'rm -rf $EMPTY/*', 'rm -rf "$EMPTY"/data']:
    print(f"{line:<26} -> {words(line)}")

Run it, and you should see this output:

$ python3 shell_words.py
cp $SRC backup/            -> ['cp', 'May', 'report.csv', 'backup/']
cp "$SRC" backup/          -> ['cp', 'May report.csv', 'backup/']
echo '$HOME' "$HOME"       -> ['echo', '$HOME', '/home/asha']
ls *.log "*.log" *.xyz     -> ['ls', 'a.log', 'b.log', '*.log', '*.xyz']
rm -rf $EMPTY/*            -> ['rm', '-rf', '/*']
rm -rf "$EMPTY"/data       -> ['rm', '-rf', '/data']

3. What to notice

4. Advanced: every step as one Bash script

The same Linux steps, made into a real script you can keep and run again. It uses the Bash features a production script needs: functions (one per step), an array of step names, arguments to choose steps, a case for options, exit codes recorded for each step, and a trap that prints a summary even when you stop it with Ctrl+C. Make a folder for this lesson (mkdir -p ~/labs/the-shell-quoting-pipes-redirects-globs-variables-and-exit-codes && cd ~/labs/the-shell-quoting-pipes-redirects-globs-variables-and-exit-codes) and save this as lab.sh.

#!/usr/bin/env bash
# The Linux steps of "The Shell Without Surprises: Quoting, Pipes, Redirects, Globs, Variables, and Exit Codes", as one script (save it as lab.sh).
#
#   ./lab.sh          run every step, in order
#   ./lab.sh 2 4      run only steps 2 and 4
#   ./lab.sh --list   list the steps
#
# The steps share one shell, so a later step can use what an earlier one set up (a folder,
# a variable, a container): run them all in order the first time. Your own scripts should
# start with "set -euo pipefail"; this one runs teaching commands, and some of them fail on
# purpose, so it records each step's exit code instead of stopping at the first failure.

STEPS=(
  'Make a lab folder and a file whose name has a space, then see what the program receives with and without quotes. printf '\''[%s]\n'\'' prints each argument it gets inside brackets.'
  'Single quotes against double quotes.'
  'Globs: the shell turns patterns into file names before the program runs.'
  'Standard output and standard error go to different places.'
  'A pipeline'\''s exit code, with and without pipefail. false always fails; true always succeeds.'
  'Guards that stop a script before an empty variable does damage. Both run in a child shell, so your own shell is unaffected, and the dangerous command is only echoed.'
  'Clean up.'
)

step_1() {
mkdir -p ~/labs/shell && cd ~/labs/shell
SRC="May report.csv"
printf 'id,total\n1,40\n' > "$SRC"
printf '[%s]\n' $SRC
printf '[%s]\n' "$SRC"
}

step_2() {
echo 'single: $HOME'
echo "double: $HOME"
}

step_3() {
touch a.log b.log notes.txt
echo *.log
echo "*.log"
echo *.xyz
}

step_4() {
ls "$SRC" nofile > out.txt 2> err.txt; echo "exit $?"
cat out.txt
cat err.txt
}

step_5() {
false | true; echo "without pipefail: $?"
set -o pipefail; false | true; echo "with pipefail: $?"; set +o pipefail
}

step_6() {
bash -c 'set -u; echo "value: $NOT_SET"'; echo "exit $?"
bash -c 'D=""; echo rm -rf "${D:?D is empty, refusing}"/*'; echo "exit $?"
}

step_7() {
cd ~ && rm -rf ~/labs/shell
ls ~/labs
}

# print a step that has to be run by hand, instead of running it
by_hand() {
  echo "  (run this one yourself: $1)"
  sed 's/^/    /'
}

RESULTS=()
run_step() {
  local n=$1 start=$SECONDS code
  printf '\n== step %d of %d: %s\n' "$n" "${#STEPS[@]}" "${STEPS[n-1]}"
  "step_$n"
  code=$?
  RESULTS+=("step $n: exit code $code, $((SECONDS - start)) s")
}

summary() {
  echo
  echo "== summary"
  local r
  for r in "${RESULTS[@]}"; do echo "  $r"; done
}

case "${1:-}" in
  -h|--help) sed -n '2,6p' "$0"; exit 0 ;;
  --list) for i in "${!STEPS[@]}"; do echo "$((i + 1)). ${STEPS[i]}"; done; exit 0 ;;
esac

[ $# -eq 0 ] && set -- $(seq 1 "${#STEPS[@]}")
for n in "$@"; do
  if ! [[ $n =~ ^[0-9]+$ ]] || (( n < 1 || n > ${#STEPS[@]} )); then
    echo "there is no step '$n'; try --list" >&2
    exit 2
  fi
done
trap summary EXIT
trap 'echo; echo "stopped with Ctrl+C"; exit 130' INT
for n in "$@"; do run_step "$n"; done

Then make it executable and run it:

chmod +x lab.sh
./lab.sh --list     # the steps
./lab.sh            # every step, then a summary of exit codes and times
./lab.sh 2 3        # only steps 2 and 3

5. Learn the basics behind it

New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.

If you remember nothing else

Design exercise

Your team's scripts folder has 40 Bash scripts that run in cron and CI. Several have failed silently this year. Design how you would make them safe.

Clarifying questions to ask

What does every script start with? How are variables, file names, and destructive commands handled? How are failures reported, and to whom? How are scripts checked before they merge? Which scripts should not be Bash at all?

Rough sizing

Say 40 scripts, 5 of them over 200 lines, run 300 times a day in total.

Shape of the answer

A template with set -euo pipefail and a usage message; quoted variables and :? guards; curl -fsS; messages on standard error and a non-zero exit on failure; shellcheck and bats tests in CI; the long scripts rewritten in Python; cron and CI alerting on non-zero exits and on suspicious output sizes.

Trade-offs to name

set -e has edge cases (it does not trigger inside some conditionals), so it is a safety net, not a replacement for checking important commands explicitly.

Failure modes and how to troubleshoot them

Each row is one way this system went wrong in the diagram's scenarios. The hop number is where to look first.

ScenarioWhereEffectWhat goes wrong
Unquoted variableHop 3: QuotingBreaksUnquoted, May report.csv is split at the space: cp receives May, report.csv, and backup/, so it looks for two files that do not exist. "cp: cannot stat 'May': No such file or directory". The script has no error check, so it goes on to print "backup complete".
Unquoted variableHop 8: Exit codeDegradescp returned 1, but the script had no set -e and no check, so it carried on.
Unquoted variableHop 9: Read itBreaksThe two cp errors scroll past; the last line says "backup complete".
Pipeline failure hiddenHop 8: Exit codeBreakscurl exits with 22 (with -f) or prints an error page; gzip exits with 0; the pipeline's status is gzip's 0. The cron job reports success every night. Nine days later a restore is needed, and backup.gz contains nothing.
Pipeline failure hiddenHop 9: Read itBreaksNo errors shown: curl -s is silent.

How to troubleshoot

  1. Write down the symptom and when it started: what users see, which number moved, and what changed just before (a deploy, a config change, traffic).
  2. Walk the path in order, from the first hop to the last: Type → Variables → Quoting → Globs → Redirects → Pipes → Run → Exit code → Read it. The first hop whose evidence is wrong is where to dig.
  3. At that hop, run the read-only check from the diagram or the lab first; change nothing until the evidence points at a cause.
  4. Fix the smallest thing that restores service, or roll back the last change, and confirm the symptom is gone with the same check.
  5. Write down what you found and the check that would have caught it sooner, so the next person starts there.

References and review

The official documentation and standards behind this lesson. Versions and defaults change; when a command or field here differs from them, trust the official page.

Last updated . Next review due by November 2027. Found something out of date? Tell me.

Saved on this device, in this browser.
Next in this series · Lesson 04
Editing Files and Working on Remote Hosts: nano, vim, and SSH Without Locking Yourself Out

Sooner or later you will change a file on a machine you can only reach over the network. SSH gives you a shell on that machine, protected by a key pair instead of a password, and a terminal editor (nano for simple edits, vim…

Go to Lesson 04 →

Or browse the full course from the Lessons index.