The most common decision shape in shell scripts:
if command; then
...
elif command; then
...
else
...
fi
if doesn't check a boolean. It checks whether the command
succeeded. Exit code 0 (success) means the then branch runs,
nonzero means skip to elif or else.
Comparing values needs a command that returns 0 or nonzero based
on the comparison. That command is test, or its more common
alias [.
if [ "$user" = "root" ]; then
echo "hi root"
fi
Read [ ... ] as "test whether...". The closing ] is
required. Spaces around [ and inside are mandatory.
Strings:
[ "$a" = "$b" ] equal[ "$a" != "$b" ] not equal[ -z "$a" ] empty[ -n "$a" ] non-emptyNumbers:
[ "$a" -eq "$b" ] equal[ "$a" -ne "$b" ] not equal[ "$a" -lt "$b" ] less than[ "$a" -le "$b" ] less than or equal[ "$a" -gt "$b" ], [ "$a" -ge "$b" ] greaterFiles:
[ -f file ] regular file exists[ -d dir ] directory exists[ -e path ] anything exists[ -r file ] readable[ -w file ] writable[ -x file ] executablename=""
if [ $name = "alice" ]; then # syntax error: [ = alice ]
Unquoted $name when empty expands to nothing, breaking the
test syntax. Always quote both sides:
if [ "$name" = "alice" ]; then
The next node shows a safer alternative that fixes this whole class of bug.