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"; fi

Each 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 ;; esac

case 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
Answer: The command list's exit status
2. When should -eq be used instead of = inside [ ... ]?
Answer: When the operands should be compared as integers rather than strings.

Keep building

Authoritative references

Make the idea retrievable.

Study this concept with spaced repetition, next to the commands where you use it.

Get Terminaster