The Analogy: The Sign-Writer's Job Envelope
A sign-writer's shop takes work in paper envelopes. Inside each envelope is a copy sheet: the exact letters to be painted, the size, the colour. Because the same sign is often produced for forty branches with only the town name changing, the shop long ago settled on a convention. Words in angle brackets are fields, looked up in the branch book at the bench. Everything else is copy, painted as it stands. Two rubber stamps on the outside of the envelope tell the bench which rules apply: SET AS WRITTEN, or FILL THE FIELDS.
SET AS WRITTEN means exactly that. The bench paints every character on the sheet, angle brackets and all, and does not open the branch book. It is the stamp you use for a sign that must read <PRESS BELL FOR SERVICE> with the brackets showing, and it is the only stamp that guarantees what leaves the shop is what you wrote. FILL THE FIELDS means the bench substitutes each bracketed field for its value from the book, and -- this is the part people forget -- leaves everything else alone, including the spacing. A field whose value is two words stays two words on one plate, because the copy sheet's layout is respected.
An envelope with no stamp at all is treated as a rough note, and the shop applies its house tidying rules. Runs of spaces are normalised to one. Blank entries are skipped rather than painted as blank plates. A shorthand in the copy such as an asterisk is read as "one sign for each item currently on the rack", which is genuinely convenient when you meant it. Old hands at the shop use unstamped envelopes deliberately, for exactly those effects, and they are careful about it in a way that new starters are not.
The failure mode is never the SET AS WRITTEN envelope. That one produces a sign reading <BRANCH> in three-inch letters, everyone laughs, and it is repainted the same afternoon. The expensive failure is the unstamped envelope. The town called Great Bookham comes back as two signs, one reading GREAT and one reading BOOKHAM, both perfectly well made. The branch with no name yet does not produce a blank plate to be filled in later; it produces nothing, so the batch of eight arrives as seven and the numbering on the delivery note no longer matches the plates. Nobody notices in the shop, because everything in the shop is correct. It is noticed at the site, by the installer, on a Sunday.
Syntax or Core Structure
Bash has three quoting states, and the difference between them is not what the text means but which rewriting stages still apply to it.
#!/usr/bin/env bash
name="Great Bookham"
printf '[%s]\n' "$name"
printf '[%s]\n' '$name'
printf '[%s]\n' $name
Output:
[Great Bookham]
[$name]
[Great]
[Bookham]
One variable, one value, three different outcomes. Double quotes expanded the parameter and then stopped, so printf received one argument. Single quotes expanded nothing, so printf received the four characters of the name of the variable. No quotes expanded the parameter and then split the result at the space, so printf received two arguments and, because a format string is reused until the arguments run out, printed two lines.
The fuller picture of what survives each state:
#!/usr/bin/env bash
who=world
printf '%s\n' "hello $who $(echo sub) $(( 2 + 2 ))"
printf '%s\n' 'hello $who $(echo sub) $(( 2 + 2 ))'
printf '%s\n' hello\ $who
printf '%s\n' "a\"b" 'a'"'"'b'
Output:
hello world sub 4
hello $who $(echo sub) $(( 2 + 2 ))
hello world
a"b
a'b
Inside double quotes, parameter expansion, command substitution and arithmetic expansion all still run, so the first line is fully processed. Inside single quotes nothing runs at all, which is why the second line prints its own source text. The third line shows the backslash, which quotes exactly one following character: hello\ $who is one argument containing a space, and it is the shortest possible way to protect a single character. The fourth line shows the two escape hatches: a double quote inside double quotes needs a backslash, and a single quote inside single quotes cannot be escaped at all -- you must close the single-quoted run, add a quoted quote, and open a new run.
One state remains, and it is the one people do not know about. $'...' is ANSI-C quoting, and it is the only form in which backslash escapes become real characters:
#!/usr/bin/env bash
plain='a\tb'
ansic=$'a\tb'
printf 'plain length %d\n' "${#plain}"
printf 'ansi-c length %d\n' "${#ansic}"
printf '%s\n' "$ansic" | cat -A
Output:
plain length 4
ansi-c length 3
a^Ib$
The single-quoted value is four characters -- a, backslash, t, b. The ANSI-C value is three, because the escape became a real tab, which cat -A renders as ^I with a $ marking the end of the line. This is how you put a tab, a newline or a specific byte into a variable without inventing a helper.
Technical Depth: What Each Kind of Quote Switches Off
The four forms side by side
| Form | Expansions that still run inside it | Cannot contain | Reach for it when |
|---|---|---|---|
| no quotes | everything, then word splitting and pathname expansion | nothing is protected | you actively want splitting or globbing |
| double quotes | parameter, command and arithmetic expansion | an unescaped double quote | almost always; this is the default |
| single quotes | none whatsoever | a single quote, by any means | regexes, awk programs, literal dollar signs |
| dollar-single | backslash escapes only, never parameters | an unescaped single quote, though a backslashed one is allowed | tabs, newlines and specific bytes |
The row that surprises people is the last one: $'$HOME' prints the five literal characters, because ANSI-C quoting processes backslash escapes and nothing else. It is not "single quotes plus expansion".
Getting a single quote inside single quotes
There is no escape character inside single quotes, so the two working techniques are worth memorising:
#!/usr/bin/env bash
a='it'\''s here'
b=$'it\'s here'
printf '%s\n' "$a"
printf '%s\n' "$b"
printf 'same: %s\n' "$([ "$a" = "$b" ] && echo yes || echo no)"
Output:
it's here
it's here
same: yes
The first form reads as four pieces glued together with no spaces between them: 'it', then a backslashed quote, then 's here'. Adjacent quoted runs concatenate, which is a rule worth knowing in its own right. The second form uses ANSI-C quoting, where a backslashed quote is legal. Both produce the same seven characters, as the comparison confirms.
The most consequential pair in the language
| Form | What the called program receives | Correct when |
|---|---|---|
"$@" | one argument per original argument, boundaries and empty strings intact | forwarding arguments; treat this as the only right answer |
"$*" | a single argument, all originals joined with the first character of IFS | assembling one string for a log line or an error message |
$@ unquoted | every argument re-split at whitespace and glob-expanded | essentially never |
$* unquoted | joined, then re-split and glob-expanded | never |
"$@" is special-cased in the grammar: it is the one expansion that can produce a different number of words depending on its contents while still being quoted. Every wrapper script, every dispatch function and every exec at the end of an entrypoint depends on it.
IFS, precisely
IFS holds the characters that word splitting uses as separators. Its default value is space, tab and newline, and it behaves differently depending on whether the separator is whitespace.
#!/usr/bin/env bash
line="alpha:beta::delta"
IFS=: read -r -a f <<< "$line"
printf 'field %d: [%s]\n' 1 "${f[0]}" 2 "${f[1]}" 3 "${f[2]}" 4 "${f[3]}"
printf 'fields: %d\n' "${#f[@]}"
ws=" alpha beta "
read -r -a w <<< "$ws"
printf 'whitespace split gives %d words: [%s][%s]\n' "${#w[@]}" "${w[0]}" "${w[1]}"
Output:
field 1: [alpha]
field 2: [beta]
field 3: []
field 4: [delta]
fields: 4
whitespace split gives 2 words: [alpha][beta]
With IFS set to a colon, every single colon is a separator, so the doubled colon in the middle yields a genuinely empty third field and the count is four. With the default whitespace IFS, runs of separators collapse into one and leading and trailing separators are discarded entirely, so the second example yields two words rather than four. This is the whole reason that parsing a colon-separated file works and that parsing a space-aligned report does not: one preserves empty fields and the other cannot represent them.
A related rule: setting IFS on the same line as the command, as IFS=: read ..., applies it to that command only. Assigning IFS on its own line changes it for the rest of the script, which is a common source of distant, baffling behaviour.
Reading a line without damaging it
| Option | What it changes |
|---|---|
-r | stops backslash being treated as an escape character |
an IFS= prefix | stops leading and trailing whitespace being trimmed |
-a name | splits the line into an indexed array instead of separate variables |
-d C | stops at character C instead of at a newline, which is how you read NUL-separated input |
-n N | returns after N characters without waiting for a newline |
-p TEXT | writes a prompt first, for interactive use only |
-s | does not echo what is typed, for passwords |
-t N | gives up after N seconds and returns a non-zero status |
The first two are not really options. They are the difference between reading a line and reading an approximation of it:
#!/usr/bin/env bash
printf '%s\n' ' a\tb ' > raw.txt
IFS= read -r keep < raw.txt
read -r trimmed < raw.txt
read cooked < raw.txt
printf 'IFS= read -r : [%s] len %d\n' "$keep" "${#keep}"
printf 'read -r : [%s] len %d\n' "$trimmed" "${#trimmed}"
printf 'read : [%s] len %d\n' "$cooked" "${#cooked}"
Output:
IFS= read -r : [ a\tb ] len 10
read -r : [a\tb] len 4
read : [atb] len 3
The file holds eleven bytes: three spaces, the four characters a\tb, three more spaces, and a newline. Only the first form gives back the ten characters that were on the line. The second silently trimmed six of them, and the third also swallowed the backslash, turning a two-character escape into nothing at all. IFS= read -r line is therefore the canonical incantation, and any script that reads text without it is guessing.
Real World Example: A Sign-Plate Batch Runner
The job envelope from the analogy is a text file, one order per line, colon separated. The runner has to read it without damaging any field, reject the malformed orders with a usable message, forward each good order to a renderer as four separate arguments, and reconcile its own counts at the end. Every rule from this lesson appears in it.
#!/usr/bin/env bash
set -u
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
cd "$work" || exit 1
cat > orders.txt <<'ORDERS'
# id : legend : width_mm : notes
GB-01:Great Bookham:820:
LH-02:Little Hampton:640:doubled space kept
ST-03:Star * Yard:455:asterisk in legend
EW-04:East Wing: :width is blank
XX-06::300:legend missing
:Orphan Plate:300:id missing
ORDERS
printf 'FN-05:Fen End:640:trailing spaces kept%s\n' ' ' >> orders.txt
warn() { printf 'reject: %s\n' "$*" >&2; }
render() {
local id=$1 legend=$2 width=$3 notes=$4
printf '%-6s %-18s %5d [%s]\n' "$id" "$legend" "$width" "$notes"
printf '%s\t%s\t%s\n' "$id" "$legend" "$width" >> manifest.tsv
}
join_ids() { local IFS=,; printf 'ids joined : [%s]\n' "$*"; }
count_ids() { printf 'ids as words: %d\n' "$#"; }
count_words() { printf 'words: %d ->' "$#"; printf ' [%s]' "$@"; printf '\n'; }
: > manifest.tsv
accepted=0 rejected=0 total=0
ids=()
printf '%-6s %-18s %5s %s\n' PLATE LEGEND WIDTH NOTES
while IFS= read -r line; do
[ -z "$line" ] && continue
case $line in '#'*) continue ;; esac
IFS=: read -r id legend width notes <<< "$line"
if [ -z "$id" ]; then
warn "line with legend [$legend] has no plate id"
rejected=$((rejected + 1)); continue
fi
if [ -z "$legend" ]; then
warn "$id has no legend"
rejected=$((rejected + 1)); continue
fi
case $width in
''|*[!0-9]*) warn "$id width [$width] is not a whole number"
rejected=$((rejected + 1)); continue ;;
esac
render "$id" "$legend" "$width" "$notes"
ids+=("$id")
accepted=$((accepted + 1))
total=$((total + width))
done < orders.txt
printf '%-6s %-18s %5d\n' '--' 'total width mm' "$total"
printf 'accepted %d, rejected %d, manifest rows %d\n' \
"$accepted" "$rejected" "$(wc -l < manifest.tsv)"
join_ids "${ids[@]}"
count_ids "${ids[@]}"
sample='Star * Yard'
count_words "$sample"
count_words $sample
Output: (standard output and standard error together, in the order bash writes them)
PLATE LEGEND WIDTH NOTES
GB-01 Great Bookham 820 []
LH-02 Little Hampton 640 [doubled space kept]
ST-03 Star * Yard 455 [asterisk in legend]
reject: EW-04 width [ ] is not a whole number
reject: XX-06 has no legend
reject: line with legend [Orphan Plate] has no plate id
FN-05 Fen End 640 [trailing spaces kept ]
-- total width mm 2555
accepted 4, rejected 3, manifest rows 4
ids joined : [GB-01,LH-02,ST-03,FN-05]
ids as words: 4
words: 1 -> [Star * Yard]
words: 4 -> [Star] [manifest.tsv] [orders.txt] [Yard]
There are two reads and they are deliberately different. The outer while IFS= read -r line pulls in a whole line with nothing trimmed and no backslash processing, which is what keeps the three trailing spaces on the FN-05 order alive all the way to the printed brackets. The inner IFS=: read -r id legend width notes then splits that one line on colons, where every single colon counts, so EW-04 keeps its two-space width field instead of having it collapsed away and the empty notes field on GB-01 stays empty rather than vanishing. Trying to do both jobs with one read is the usual mistake: with IFS set to a colon for the outer read, the loop would still work, but you would have lost the ability to see the raw line in an error message.
Quoting carries the rest of the weight. render receives four arguments because all four are quoted at the call site; Little Hampton arrives with its doubled space intact and Star * Yard arrives as text rather than as a directory listing. The two count_words calls at the end are the proof, and they are the only place in the program where an unquoted expansion is deliberate: the same three-word string is one argument when quoted and four arguments when not, because the asterisk matched the two files that happen to be in the scratch directory. Notice also that warn uses "$*" rather than "$@", which is correct here for once, because a warning is a single message and not an argument list.
The counters are the audit trail. Four accepted rows are printed, four rows are appended to the manifest, and wc -l on that manifest agrees, so the summary line reconciles against itself rather than against a number the program hopes is right. The widths shown sum to 820 plus 640 plus 455 plus 640, which is the 2555 printed underneath, and the width column is right-aligned to the same character position as the header because every row goes through one %5d format. Validation happens before the plate is drawn and each check rejects on the first failure, which is why XX-06 never reaches the digit test. The digit test itself is a case pattern rather than a regex, which is worth doing because it needs no external process and no special characters to escape.
The genuine limits are worth stating plainly, because this program has a real bug and not merely rough edges. A colon inside a legend silently shifts every later field, and the result can pass validation. The order GB-08:Bookham Rd:2:820:mm plate parses as legend Bookham Rd, width 2 and notes 820:mm plate; two millimetres is a whole number, so the runner accepts it and renders a plate that nobody ordered. There is no escaping mechanism in the format and no check that could catch it, since the shifted value is indistinguishable from a legitimate one. Beyond that: set -u is on but set -e and pipefail are not, so a failing printf into the manifest would be ignored; the manifest is appended row by row with no rollback, so a crash midway leaves a partial file that the next stage cannot tell from a complete one; and the width check accepts 0 and 999999 as readily as 820, because "is a whole number" is not the same question as "is a plausible plate width".
Common Mistakes
- Leaving a variable unquoted because "it cannot contain spaces". Every unquoted expansion is a promise about data you have not seen yet.
cp $src $dstworks for months and then one filename arrives with a space in it and the command silently copies the wrong thing, or two things, or nothing. The habit to build is the reverse of the intuitive one: quote by default, and treat every unquoted expansion as something that needs a reason.
- Writing
$*where"$@"is meant. Both look like "all the arguments". Only"$@"preserves how many there were. A wrapper that forwards with$*or"$*"will passfive filesas one argument or re-splitGreat Bookhaminto two, and the failure appears in the called program, which makes it look like the called program's bug.
- Using
readwithout-r. Plainreadtreats a backslash as a line-continuation and escape character, so a Windows path, a regex, or anything with\tin it comes back mangled. It is a silent corruption, not an error, and there is essentially no situation in a script where the escape processing is what you wanted.
- Using
readwithout theIFS=prefix. Without it, leading and trailing whitespace is trimmed from every line you read. Fixed-width reports, indented configuration files and anything where alignment is data all lose information before your code ever sees it.IFS= read -r lineshould be a single reflex.
- Expecting anything at all to expand inside single quotes.
echo 'Total: $total'prints the six characters of the variable's name. There is no partial expansion, no exception for command substitution and no escape character. When you need part literal and part expanded, close the quote and reopen it:'Total: '"$total".
- Trying to backslash a single quote inside single quotes.
'it\'s'does not do what it looks like; the backslash is literal and the quote ends the string, leaving bash waiting for a matching quote or gluing on whatever follows. Use'it'\''s'or$'it\'s'. Nothing else works.
- Assigning IFS on its own line instead of on the command.
IFS=:as a statement changes splitting for the rest of the script, including inside functions called much later and including the"$*"joins in your logging. The symptom appears hundreds of lines away from the cause. Put the assignment on the command that needs it:IFS=: read -r a b c.
- Feeding
lsinto aforloop.for f in $(ls *.txt)runsls, captures its output as one string, then word splits and globs that string. Filenames with spaces break into pieces and filenames containing an asterisk get expanded a second time.for f in *.txtneeds no subprocess and produces exactly one word per file, whatever is in the name.
- Quoting the glob so it never happens.
rm "*.tmp"does not delete temporary files; it looks for one file literally named asterisk-dot-tmp. Pathname expansion is one of the few things that quotes switch off and that you usually want on, which is exactly why the guidance is "quote expansions", not "quote everything".
Best Practices
- Quote every expansion by default, and make each unquoted one deliberate. If an expansion is unquoted on purpose, say so in a comment on that line. A reader should never have to guess whether the missing quotes were a decision or an oversight.
- Forward arguments with
"$@"and nothing else. It is the one form that keeps the argument count, the empty strings and the internal spacing. Reserve"$*"for building a single human-readable message, as thewarnfunction above does.
- Learn
IFS= read -r lineas one token. Type it as a unit. The two halves protect against different kinds of damage, and code that has one but not the other is usually a copy of something that had neither.
- Prefer single quotes for anything containing a dollar sign. awk programs, sed scripts, regexes and format strings are all safer inside single quotes, where the shell cannot touch them. It removes a whole class of "why is my regex empty" problems.
- Use
printfrather thanechofor anything with structure.echodiffers between shells and builds over how it handles-n,-eand leading dashes.printf '%s\n' "$var"behaves identically everywhere and cannot be confused by a value that starts with a hyphen.
- Set IFS on the command, or save and restore it.
IFS=, read ...is scoped to that command;local IFS=,is scoped to that function. If you truly need a global change, save the old value first and put it back, because everything downstream depends on it.
- Reach for
$'...'when you need a specific byte.$'\t',$'\n'and$'\x1b'are unambiguous and portable within bash, whereasecho -eis not. It is also the readable way to set IFS to a tab:IFS=$'\t'.
- Print values inside brackets while debugging.
printf '[%s]\n' "$x"shows you the boundaries, so an unexpected trailing space or an empty string is visible instead of invisible. Most quoting bugs are diagnosed the moment the whitespace becomes legible.
Practice Exercises
- Break it, then fix it. Create a file whose name contains a space and an asterisk. Write a two-line script that copies it using unquoted expansions, run it, and record exactly what happened and why. Then quote the expansions and confirm the copy succeeds. Keep both versions side by side as a reference.
- Prove the
"$@"difference. Write a functioncountthat prints$#and each argument in brackets, then call it four ways with the same three-element list:"$@","$*",$@and$*, where one element contains two spaces and another is the empty string. Write down the four counts before you run it and check your predictions.
- Parse a colon-separated file correctly. Take a file in the style of
/etc/passwdwith at least one empty field and one field containing spaces. Read it withwhile IFS= read -r lineplus an innerIFS=: read -r, print each record with every field bracketed, and assert that the field count is the same on every line.
- Recover a damaged read. Write a line containing leading spaces, a literal
\tbackslash-t sequence, and trailing spaces into a file. Read it three ways --read,read -randIFS= read -r-- printing the length each time. Explain, in one sentence per case, which characters were lost and which option was responsible.