Terminal · intermediate
Shell conditionals
Shell conditionals choose commands by evaluating the exit status of command lists, including test utilities and pattern-based case clauses.
Why it matters
The shell does not require a special Boolean value: understanding status-driven conditions prevents string, numeric, and filesystem tests from being mixed incorrectly.
Mental model
How to reason about shell conditionals
Run the condition as a command; select the then branch if its status is zero, otherwise evaluate later branches or the else branch.
Analogy
A conditional is a routing gate controlled by an inspector's pass or fail status rather than by printed words such as true or false.
Examples
See the boundary, not just the happy path
Worked example · Check a readable regular file
if [ -f "$config" ] && [ -r "$config" ]; then load "$config"; fiEach test command reports status, and quoting keeps an empty or spaced pathname as one operand.
Worked example · Match an option with case
case $1 in --json) format=json ;; --text) format=text ;; *) usage >&2; exit 64 ;; esaccase compares one word against shell patterns and makes the unmatched fallback explicit without executing external test commands.
Useful contrast · String versus numeric comparison
[ "$count" = 10 ] versus [ "$count" -eq 10 ]= compares strings while -eq performs an integer comparison and can reject a nonnumeric operand.
Common mistakes
Misconceptions to remove early
Omitting required test spacing
[ is a command whose closing ] is an argument, so ["$x"=yes] is not equivalent to [ "$x" = yes ].
Testing printed output instead of command status
Use if command; then directly when the command's documented status expresses the condition; parsing its prose adds fragility.
Quick check
Can you predict the result?
1. What does an if command list use as its condition result?
- • The command list's exit status
- • Whether stdout is nonempty
- • Whether stderr is empty
2. When should -eq be used instead of = inside [ ... ]?
Keep building