Tests & Conditionals
Conditionals
if [ -f /etc/passwd ]; then
echo 'exists'
elif [ -d /tmp ]; then
echo 'dir'
else
echo 'neither'
fi
| Test | True when |
|---|
-f file | file exists (regular) |
-d dir | directory exists |
-e path | path exists (any type) |
-r/-w/-x | readable/writable/executable |
-z str | string is empty |
-n str | string is non-empty |
n1 -eq n2 | numbers equal (-ne -lt -le -gt -ge) |
s1 = s2 | strings equal (!= not equal) |
$ [ 5 -gt 3 ] && echo yes
yes
Exam trap: Use -eq/-lt/-gt for numbers, =/!= for strings. [ "$a" = "$b" ] - quote variables to survive empty values and spaces.