The Analogy: The Goods-Inward Inspector's Checklist
A warehouse receiving dock employs an inspector who stands between every delivery truck and the storage floor. The inspector carries a clipboard with a printed checklist: is the tamper seal intact, is the cargo temperature within range, does the item count match the manifest, and is the supplier on the approved list. Each question has exactly two outcomes -- pass or fail -- and the inspector answers them in order, top to bottom. The first failure that matters enough to block the shipment stops the walk-through early. If every line passes, the goods move to storage. A shell conditional is that clipboard: a sequence of yes-or-no questions, each answered by running a command and reading its exit status, with a branch of work attached to each answer.
The inspector does not open every crate the same way. Some checks are quick visual tests such as "is the seal broken", some require a measuring instrument such as a thermometer or a counting scale, and some require cross-referencing a separate ledger kept in the office. The inspector picks the right instrument for the question. Using a thermometer to count boxes would be absurd, and reading the approved-supplier ledger to judge temperature would be meaningless. Bash gives you three instruments in the same way: the [ test command for files and simple strings, the [[ keyword for patterns and safe variable handling, and the (( construct for arithmetic. Each answers a specific category of question, and the skill is knowing which one the question belongs to.
Some conditions are compound. The temperature must be above 2 and below 8 degrees, and the truck must arrive before the shift cutoff, or else carry an after-hours waiver. The inspector evaluates these with short-circuit logic: if the temperature is already out of range there is no point in checking the waiver, so that check is skipped. The clipboard also allows a negated line -- "if the supplier is NOT on the restricted list, accept" -- which flips a single result without changing anything else. Bash combines and negates test results the same way, with &&, ||, and !, and it stops as soon as the outcome is settled.
The failure mode is the mismatched instrument, and it is quiet. If the inspector reads a temperature of 4.7 on the thermometer but records it in the box on the form meant for a whole-number crate count, nothing beeps -- a later clerk simply reads "4 crates" and files it. In the shell the same silent slip happens when you compare numbers with the string operators or strings with the numeric ones: comparing "10" and "9" with the text operator reports that 10 is not greater, because text sorts "1" before "9". The test runs, returns a clean status, and the wrong branch executes. Nothing in the machinery tells you the instrument was wrong for the question, so this lesson spends most of its length on which instrument belongs to which kind of check.
Syntax or Core Structure
The core control structure is if, and what it tests is not a boolean expression but the exit status of a command. The command after if runs; if it exits 0 the then branch runs, otherwise control falls through to elif or else. The [ you usually see there is not punctuation -- it is a command named [, a synonym for test, whose last argument must be ].
#!/usr/bin/env bash
printf 'depth 18\nvalve open\n' > gauge.log
reading=18
if [ "$reading" -gt 20 ]; then
printf 'over tolerance\n'
elif [ "$reading" -ge 15 ]; then
printf 'within tolerance\n'
else
printf 'under tolerance\n'
fi
if grep -q valve gauge.log; then
printf 'grep found valve, so this branch ran\n'
fi
if [ -f gauge.log ] && [ -s gauge.log ]; then
printf 'gauge.log exists and is not empty\n'
fi
if [ -f missing.log ]; then
printf 'not reached\n'
else
printf 'missing.log is not a regular file\n'
fi
The second if shows the point that trips up newcomers: there is no [ at all. grep -q valve gauge.log is just a command, and if branches on whether it succeeded. The [ in the other branches is one option among many, not a required part of the syntax.
Output:
within tolerance
grep found valve, so this branch ran
gauge.log exists and is not empty
missing.log is not a regular file
Technical Depth: The Three Instruments and What Each One Reads
Bash has three separate mechanisms for asking a yes-or-no question, and they are not interchangeable. Ask type -t what each one is and the shell tells you their nature directly.
#!/usr/bin/env bash
type -t if
type -t [
type -t [[
type -t '(('
Output:
keyword
builtin
keyword
keyword
[ is an ordinary builtin command: it receives its arguments after the shell has already split words and expanded globs, exactly as ls would. [[ and (( are keywords, parsed by the shell itself, so the shell can suppress word splitting and glob expansion inside them. That single difference explains most of the behaviour below.
The three questions and the operators that ask them
Each instrument owns a family of operators. Mixing them is the classic silent bug, so the table keys each operator to the construct it belongs in and the kind of value it reads. The string ordering operators are shown by name because a literal angle bracket cannot appear in a table cell.
| Question | Construct | Operators | Reads |
|---|---|---|---|
| Does this file exist, and what kind | test or double-bracket | -e -f -d -L -r -w -x -s | a pathname |
| Are two strings equal or ordered | test or double-bracket | = != -z -n plus less-than, greater-than | text |
| Does a string match a pattern | double-bracket only | == != =~ | text plus glob or regex |
| Are two integers ordered | test or double-bracket | -eq -ne -lt -le -gt -ge | whole numbers as text |
| Is an arithmetic result non-zero | double-paren | numeric compare, logic, negation | numbers |
The trap sits in the middle rows. Integers are compared with the word-like operators -lt and -gt, while strings are ordered with the angle-bracket symbols. Inside (( those same symbols mean numeric comparison again. So the greater-than symbol means "sorts after" in [[ but "is numerically larger" in ((, and it gives opposite answers for 10 and 9.
File tests read the filesystem, not the string
The file operators ask the kernel about a pathname. This harness sets up a directory, a regular file, and an empty file, then prints one column per test so you can see which flags fire for each kind of entry.
#!/usr/bin/env bash
mkdir -p testdir
printf 'hello' > testdir/data.txt
rm -f empty.txt; touch empty.txt
for f in testdir/data.txt empty.txt missing.txt testdir; do
exists="-"; regular="-"; directory="-"
readable="-"; writable="-"; notempty="-"
[ -e "$f" ] && exists="e"
[ -f "$f" ] && regular="f"
[ -d "$f" ] && directory="d"
[ -r "$f" ] && readable="r"
[ -w "$f" ] && writable="w"
[ -s "$f" ] && notempty="s"
printf '%-18s %s %s %s %s %s %s\n' "$f" \
"$exists" "$regular" "$directory" "$readable" "$writable" "$notempty"
done
Output:
testdir/data.txt e f - r w s
empty.txt e f - r w -
missing.txt - - - - - -
testdir e - d r w -
Read the columns: missing.txt fails every test because there is nothing to inspect. empty.txt passes -e, -f, -r, -w but fails -s, because -s means "exists and has size greater than zero". testdir passes -d and fails -f. The distinction between -e (exists as anything) and -f (exists as a regular file) is the one people skip, and it matters: a directory or a named pipe passes -e but not -f. On a Linux system with real symbolic links, -L tests whether the name itself is a link, while -f and -e follow the link and report on its target.
String tests, and why the quotes are not optional in [
Because [ is a plain command, it never sees your variable -- it sees the words the variable expanded into, after splitting. Quoting keeps an empty or space-containing value as exactly one argument.
#!/usr/bin/env bash
a="apple"
b="banana"
[ "$a" = "$b" ]; printf 'equality: %d\n' "$?"
[ "$a" != "$b" ]; printf 'inequality: %d\n' "$?"
[ -z "" ]; printf 'zero length: %d\n' "$?"
[ -n "$a" ]; printf 'non-zero length: %d\n' "$?"
count=5
[ "$count" -ge 1 ] && [ "$count" -le 10 ]
printf 'range with two tests: %d\n' "$?"
Output:
equality: 1
inequality: 0
zero length: 0
non-zero length: 0
range with two tests: 0
The ordering operators inside [ also carry a hazard: an unescaped angle bracket is a redirection to the shell, so it would try to open a file named after the second string instead of comparing. You must backslash-escape it, which is one more reason string ordering is better done inside [[. And if $a were unquoted and empty, [ -n $a ] would collapse to [ -n ], which tests whether the string -n is non-empty and returns 0 -- the opposite of what you meant.
[[ suppresses splitting, and adds patterns
Inside the [[ keyword the shell does not split words or expand globs on the operands, so an unquoted variable holding spaces stays a single value. [[ also adds two operators [ does not have: == for glob matching and =~ for regex, the latter filling the BASH_REMATCH array with the whole match and each captured group.
#!/usr/bin/env bash
host="web-server-04"
[[ $host == web-* ]]; printf 'glob match: %d\n' "$?"
[[ $host == db-* ]]; printf 'glob mismatch: %d\n' "$?"
[[ $host =~ ^web-server-([0-9]+)$ ]]
printf 'regex match: %d\n' "$?"
printf 'whole match: %s\n' "${BASH_REMATCH[0]}"
printf 'group 1: %s\n' "${BASH_REMATCH[1]}"
path="has spaces/file.txt"
[[ -n $path ]]; printf 'unquoted here is safe: %d\n' "$?"
Output:
glob match: 0
glob mismatch: 1
regex match: 0
whole match: web-server-04
group 1: 04
unquoted here is safe: 0
One subtlety: on the right of == a quoted string is a literal, an unquoted one is a glob pattern. Writing the pattern in quotes asks whether the host equals the exact literal text including the star, while leaving it unquoted asks whether the host starts with web-. The same rule applies to the regex on the right of =~: quote it and the metacharacters become literal.
(( is for numbers, and zero is false
The arithmetic construct evaluates a C-like expression and sets its exit status from the result: a non-zero value yields status 0 (success), and a value of zero yields status 1. This inverts the intuition from other languages, so it deserves a demonstration.
#!/usr/bin/env bash
temp=72; low=60; high=80
if (( temp >= low && temp <= high )); then
printf 'in range\n'
fi
if (( (temp - low) * 100 / (high - low) > 50 )); then
printf 'above midpoint\n'
fi
(( result = temp > 70 ? 1 : 0 ))
printf 'ternary result: %d\n' "$result"
(( 0 )); printf 'value 0 gives status: %d\n' "$?"
(( 7 )); printf 'value 7 gives status: %d\n' "$?"
Output:
in range
above midpoint
ternary result: 1
value 0 gives status: 1
value 7 gives status: 0
Inside (( you do not prefix variables with a dollar sign to read them, integer division truncates toward zero, and there is no word splitting, so (( x > 5 )) is safe even when x is empty -- an empty operand is treated as 0. That makes (( the correct instrument whenever the question is genuinely about magnitude.
Real World Example: A Release Gate That Picks the Right Instrument
A deployment pipeline should refuse to ship when preconditions are not met. The gate below inspects a build tree the way the goods-inward inspector works the dock: file existence with the file operators, a build marker with a string match, a version string parsed with a regex, and a port value judged with arithmetic. Each check uses the instrument that fits its question, and each failure is counted rather than aborting the walk-through, so the operator sees the whole picture in one pass.
#!/usr/bin/env bash
# deploy-gate.sh -- check preconditions before a release
set -u
work=$(mktemp -d); trap 'rm -rf "$work"' EXIT
mkdir -p "$work/build" "$work/config"
printf 'OK\n' > "$work/build/status.txt"
printf 'v3.8.1\n' > "$work/build/version.txt"
printf 'port=443\n' > "$work/config/tls.conf"
printf 'level=warn\n' > "$work/config/log.conf"
# db.conf is deliberately left missing
required_files=(
"$work/build/status.txt" "$work/config/tls.conf"
"$work/config/log.conf" "$work/config/db.conf"
)
warn=0 fail=0
printf '=== file checks ===\n'
for f in "${required_files[@]}"; do
tag=${f##*/}
if [ ! -e "$f" ]; then
printf ' FAIL %-14s missing\n' "$tag"; fail=$((fail + 1))
elif [ ! -s "$f" ]; then
printf ' WARN %-14s empty\n' "$tag"; warn=$((warn + 1))
else
printf ' OK %-14s present\n' "$tag"
fi
done
printf '=== build status ===\n'
if [[ $(cat "$work/build/status.txt") == OK ]]; then
printf ' build: passed\n'
else
printf ' build: not OK\n'; fail=$((fail + 1))
fi
printf '=== version check ===\n'
version=$(cat "$work/build/version.txt")
if [[ $version =~ ^v([0-9]+)\.([0-9]+)\.([0-9]+)$ ]]; then
major=${BASH_REMATCH[1]}; minor=${BASH_REMATCH[2]}; patch=${BASH_REMATCH[3]}
printf ' parsed: major=%d minor=%d patch=%d\n' "$major" "$minor" "$patch"
if (( major < 3 )); then
printf ' FAIL version %s below minimum 3.0.0\n' "$version"; fail=$((fail + 1))
elif (( major == 3 && minor < 5 )); then
printf ' WARN version %s below preferred 3.5.0\n' "$version"; warn=$((warn + 1))
else
printf ' OK version %s meets threshold\n' "$version"
fi
else
printf ' FAIL version does not match pattern\n'; fail=$((fail + 1))
fi
printf '=== port check ===\n'
port_line=$(grep -E '^port=' "$work/config/tls.conf" 2>/dev/null || true)
port=${port_line#port=}
if [ -z "$port_line" ]; then
printf ' FAIL no port directive\n'; fail=$((fail + 1))
elif (( port == 443 )); then
printf ' OK TLS port %d\n' "$port"
elif (( port >= 1024 && port <= 65535 )); then
printf ' WARN non-standard port %d\n' "$port"; warn=$((warn + 1))
else
printf ' FAIL invalid port %d\n' "$port"; fail=$((fail + 1))
fi
printf '=== summary ===\n'
printf ' warnings: %d failures: %d total issues: %d\n' \
"$warn" "$fail" "$((warn + fail))"
if (( fail > 0 )); then printf 'BLOCKED\n'; exit 1; fi
printf 'PASSED\n'
Output:
=== file checks ===
OK status.txt present
OK tls.conf present
OK log.conf present
FAIL db.conf missing
=== build status ===
build: passed
=== version check ===
parsed: major=3 minor=8 patch=1
OK version v3.8.1 meets threshold
=== port check ===
OK TLS port 443
=== summary ===
warnings: 0 failures: 1 total issues: 1
BLOCKED
Read the run against the setup. Three files exist and pass, db.conf is missing and raises one failure. The build marker is the literal OK, so the string match succeeds. The version v3.8.1 parses into three captured groups, and the arithmetic on major and minor clears both thresholds. The port is exactly 443, so the equality branch fires before the range branch is even evaluated. With one failure counted, the gate prints BLOCKED and exits 1, which is what a pipeline step needs to halt the deploy.
Notice which instrument does which job. The file loop uses [ because the questions are about pathnames and the operands are already quoted. The build and version checks use [[ because one is a pattern comparison and the other is a regex with captures, neither of which [ can do. The port comparisons use (( because the question is numeric ordering, and using string operators there would be the exact silent bug this lesson warns about -- a port of "1000" would sort as less than "443" under text comparison.
The script also shows honest limits, and one of them is a real defect. Both the clean path and the warnings-only path exit 0: a deploy that shipped with three empty config files looks identical, by exit code, to a spotless one, so a caller that keys only on the exit code cannot tell "shipped with warnings" from "shipped clean". A second flaw is the grep ... || true: it swallows a genuine grep failure such as a permission-denied config alongside the harmless "pattern not found" case, so a config the script cannot read is reported as "no port directive" rather than as the access error it actually is. Finally, the thresholds and the required-file list are baked into the script body, so a new minimum version or an extra required file means editing code rather than a config value -- fine for a fixed pipeline, brittle the moment two teams want different gates.
Common Mistakes
- Comparing numbers with the string operators. The angle-bracket operators in
[and[[compare text, so 10 sorts before 9 and "is 10 greater than 9" answers no. Use-gt,-lt, and their kin in[, or the arithmetic((for magnitude questions. The test runs cleanly and silently takes the wrong branch, which is why this is the most dangerous mistake on the list.
- Leaving a variable unquoted inside
[. Because[is a plain command,[ -n $x ]with an emptyxbecomes[ -n ], which is true, and[ $x = yes ]with a value that has spaces becomes a syntax error. Always quote operands in[, or switch to[[where splitting is suppressed.
- Assuming an unquoted right side of
==is a literal. In[[ $f == *.txt ]]the right side is a glob pattern, so this matches any name ending in.txt. If you meant the literal string*.txt, quote it. People quote it out of habit and then wonder why the wildcard stopped working.
- Forgetting that
((treats zero as false.if (( count )); thenruns the branch only whencountis non-zero, which is often the opposite of a beginner's guess. And(( x = 0 ))as the last command of a function makes the function return status 1, because the assigned value is zero.
- Using
-aand-oinside[to combine tests. The forms[ cond1 -a cond2 ]are ambiguous to parse and are deprecated by the standard. Chain separate commands with&&and||, as in[ cond1 ] && [ cond2 ], or use[[ cond1 && cond2 ]].
- Writing
[[ $a = $b ]]expecting string equality when$bholds a pattern. On the right of=or==inside[[, an unquoted variable is still treated as a pattern, so a$bof*matches everything. Quote the right operand when you want a plain equality test:[[ $a == "$b" ]].
- Testing exit status against strings.
if [ "$?" = "0" ]works but is fragile and rarely what you want; branch on the command directly withif mycmd; then, or capture the status into a variable immediately if you must inspect it later, because$?is overwritten by the very next command.
- Using
==inside single-bracket[.[ "$a" == "$b" ]happens to work in bash as an extension but is not portable and fails undersh. The standard operator for[is a single=. Reserve==for[[, where it is the documented spelling.
- Quoting a regex on the right of
=~.[[ $s =~ "^[0-9]+$" ]]treats the whole thing as a literal string to find, so the anchors and the quantifier lose their meaning. Leave the pattern unquoted, or put it in a variable and use the variable unquoted:re='^[0-9]+$'; [[ $s =~ $re ]].
Best Practices
- Reach for
[[by default in bash scripts. It suppresses word splitting and glob expansion on operands, adds pattern and regex matching, and lets you use&&and||inside the brackets. Reserve plain[for scripts that must run under POSIXsh.
- Use
((for every numeric comparison. It reads naturally, treats an empty variable as 0, and cannot be fooled by the string-ordering trap. If the question is about magnitude, the arithmetic construct is the right instrument.
- Quote every variable inside
[. Even when you are sure a value has no spaces today, quoting costs nothing and prevents the empty-operand and word-splitting failures that turn into silently wrong branches later.
- Branch on commands, not on captured statuses. Prefer
if mycmd; thenover runningmycmdand testing$?, because$?is easy to clobber with an intervening command and the direct form reads as the question you are actually asking.
- Anchor your regexes. An unanchored
=~pattern matches anywhere in the string, so[[ 9v3x =~ [0-9]+ ]]succeeds. Add^and$when you mean the whole string, and pull the pattern into a variable when it grows complex.
- Prefer
-eor-fdeliberately, not interchangeably. Decide whether you care that the path exists at all or specifically that it is a regular file, and use the operator that says so. The gap between them is where "the config is there" bugs hide.
- Keep compound conditions readable. A long chain of
&&and||is hard to audit; group related tests into a well-named function that returns a status, and let theifcall the function. The reader sees intent, not a wall of brackets.
- Return an honest, distinct exit status. If callers need to tell "clean" from "passed with warnings", give those outcomes different exit codes rather than collapsing both to 0. An exit status is the only thing the next pipeline stage can see.
Practice Exercises
- The instrument audit. Write a script that declares
a="10"andb="9"and prints the result of comparing them four ways: string ordering in[, string ordering in[[, integer ordering with-gt, and arithmetic in((. Label each line and explain in a comment why the two string comparisons disagree with the two numeric ones.
- A safe file classifier. Write a function
classifythat takes one pathname and prints one ofmissing,empty-file,file,directory, orother, using only the file-test operators and correct quoting. Test it against a regular file, an empty file, a directory, and a name that does not exist, and confirm each lands in the right bucket.
- A version comparator. Write a script that reads two version strings of the form
vMAJOR.MINOR.PATCH, validates each with a=~regex that captures the three numbers, and prints which version is newer by comparing the captured fields numerically with((. Reject any input that does not match the pattern with a clear message and a non-zero exit.
- Refactor the gate's exit codes. Take the release gate from this lesson and change it so that a clean run exits 0, a warnings-only run exits 2, and a failure exits 1. Then write a short caller that runs the gate and prints
deploy,deploy with review, orholdbased only on the gate's exit status, proving the three outcomes are now distinguishable.