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
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.
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.
Pick how the variable is written, whether the script stops on errors, and how the pipeline reports failure.
Three questions. No score is saved anywhere — this is just you against the material.
Working in the shell grows in four levels: running commands, combining them, writing safe scripts, and reviewing others' scripts.
At the basic level you can run a command and read what it says.
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 $?.
At the intermediate level you build answers out of small tools.
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.
At the advanced level your scripts fail loudly and never surprise you.
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.
At the master level you know when the shell is the wrong tool.
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.
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.
This is a composite of a failure pattern that keeps repeating; the details are illustrative. The backup that was always green.
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.
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.
Type each one, read what it prints, and compare it with the note above it.
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.
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"
Single quotes against double quotes.
echo 'single: $HOME' echo "double: $HOME"
Globs: the shell turns patterns into file names before the program runs.
touch a.log b.log notes.txt echo *.log echo "*.log" echo *.xyz
Standard output and standard error go to different places.
ls "$SRC" nofile > out.txt 2> err.txt; echo "exit $?" cat out.txt cat err.txt
A pipeline's exit code, with and without pipefail. false always fails; true always succeeds.
false | true; echo "without pipefail: $?" set -o pipefail; false | true; echo "with pipefail: $?"; set +o pipefail
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.
bash -c 'set -u; echo "value: $NOT_SET"'; echo "exit $?"
bash -c 'D=""; echo rm -rf "${D:?D is empty, refusing}"/*'; echo "exit $?"Clean up.
cd ~ && rm -rf ~/labs/shell ls ~/labs
shell_words.pyThis 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']
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
New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.
mkdir, rm, touch, cat, echo, ls, cd, Pipes, Redirection, If...Else, Exit codes, Variables.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.
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?
Say 40 scripts, 5 of them over 200 lines, run 300 times a day in total.
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.
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.
Each row is one way this system went wrong in the diagram's scenarios. The hop number is where to look first.
| Scenario | Where | Effect | What goes wrong |
|---|---|---|---|
| Unquoted variable | Hop 3: Quoting | Breaks | Unquoted, 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 variable | Hop 8: Exit code | Degrades | cp returned 1, but the script had no set -e and no check, so it carried on. |
| Unquoted variable | Hop 9: Read it | Breaks | The two cp errors scroll past; the last line says "backup complete". |
| Pipeline failure hidden | Hop 8: Exit code | Breaks | curl 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 hidden | Hop 9: Read it | Breaks | No errors shown: curl -s is silent. |
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.