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

← All Bash builtins · Linux commands