Control Flow and LogicLesson 2.1
Bash if statements and test conditions
if elif else syntax, test command, [ ] vs [[ ]], string comparison, numeric comparison operators, file test operators, compound conditions
if Statements in Bash
Bash if evaluates the exit code of a command. Zero (success) = true. Non-zero = false. The [[ ]] test construct is the modern replacement for the old [ ] — use it unless you specifically need POSIX portability.
#!/usr/bin/env bash
file="/etc/hosts"
if [[ -f "$file" ]]; then
echo "File exists"
elif [[ -d "$file" ]]; then
echo "It's a directory"
else
echo "Not found"
fiComparison Operators
# String comparisons
[[ "$a" == "$b" ]]
[[ "$a" != "$b" ]]
[[ -z "$a" ]] # true if empty string
[[ -n "$a" ]] # true if non-empty
# Numeric comparisons
[[ $x -eq $y ]] # equal
[[ $x -ne $y ]] # not equal
[[ $x -lt $y ]] # less than
[[ $x -ge $y ]] # greater than or equal
# File tests
[[ -f "$path" ]] # is regular file
[[ -d "$path" ]] # is directory
[[ -r "$path" ]] # is readable
[[ -x "$path" ]] # is executableCompound Conditions
# AND
if [[ -f "$file" && -r "$file" ]]; then
cat "$file"
fi
# OR
if [[ $USER == "root" || $EUID -eq 0 ]]; then
echo "Running as root"
fiNever use == for numeric comparison — use -eq. String == on numbers works but can break with leading zeros.
