testing
test / [ ]
POSIX conditional expression evaluator — tests file attributes, string comparisons, and integer comparisons, returning exit status 0 (true) or 1 (false). [ is a command (with a required closing ]), not syntax — arguments must be separated by spaces.
test EXPR | [ EXPR ] Common flags / operators
| Flag / Operator | Purpose |
|---|---|
| -f / -d / -e | File is regular / directory / exists |
| -r / -w / -x | File is readable / writable / executable |
| -z / -n | String is zero-length / non-zero-length |
| = != | String equality / inequality |
| -eq -ne -lt -le -gt -ge | Integer comparisons |
| -a / -o | AND / OR (deprecated — use && / || between two [ ] instead) |
Examples
[ -f /etc/hosts ] && echo exists File-existence test in the classic form.
[ "$a" = "$b" ] && echo equal String compare — quote both sides to survive empties.
[ "$n" -gt 10 ] Integer >; -gt is numeric, > would be string compare.
[ -z "$var" ] && echo unset_or_empty True when var is empty.
Gotcha
Unquoted variables inside [ ] cause syntax errors when empty ('[ = foo ]'). Use =/!= (string) vs -eq/-ne (integer) correctly, and prefer [[ ]] in bash for safer parsing.
Related
[[ ]]
Bash-specific conditional expression with safer parsing, glob and regex matching, and short-circuit logical operators. No word splitting or filename expansion happens on the arguments, so quoting is far less error-prone than [ ] — but [[ ]] is not POSIX.
(( )) arithmetic
Bash arithmetic evaluation — treats operands as integers and supports C-style operators (+, -, *, /, %, **, <<, >>, &, |, ^, &&, ||, !, ==, !=, <, >, ternary). (( )) returns exit status 0 if EXPR is non-zero, 1 if zero; $(( )) substitutes the result as a string.
if / then / elif / else / fi
Conditional branching based on the exit status of a command (0 = true, non-zero = false). Runs the then-branch when the tested command succeeds; supports optional elif and else clauses and must be terminated with fi.