Control Flow
Branch on conditions using test expressions and case statements.
if / elif / else
if [[ $user == "admin" ]]; then
echo "welcome"
elif [[ -n ${user:-} ]]; then
echo "hi $user"
else
echo "anonymous"
fi
Use [[ ... ]] in Bash for safer tests (no glob expansion, better operators).
Test syntaxes
[[ ... ]]Bash keyword (preferred)[ ... ]POSIX test (single bracket)test ...command
Common string tests in [[:
[[ -z $s ]]empty,[[ -n $s ]]non-empty[[ $a == $b ]]equality (quote variables)[[ $s == foo* ]]glob match;=~for regex
File tests
[[ -f file ]] # regular file
[[ -d dir ]] # directory
[[ -s file ]] # size > 0
[[ -r file ]] # readable; -w writable; -x executable
case patterns
case "$1" in
start|up) echo starting ;;
stop|down) echo stopping ;;
*) echo "usage: $0 {start|stop}" ;;
esac
Patterns use shell globs; separate with |.
Short‑circuit operators
cmd || echo "failed"
check && deploy
|| runs the right side if the left fails (non‑zero); && runs on success.
Arithmetic conditions
x=3; y=5
if (( x < y )); then echo less; fi
(( ... )) evaluates arithmetic without $ sigils on variables.
Exit status
Commands return 0 on success, non‑zero on failure. Use $? to read the last status.
Summary
- Prefer
[[for tests; use file and string operators - Use
casefor multiple patterns; rely on&&/||for compact control flow