Quiz Entry - updated: 2026.06.20
What is the syntax for if/then/else statements in Bash?
if CONDITION; then ... else ... fi — note the semicolon (or newline) before then, and that the block closes with fi ("if" reversed).
The thing that surprises people is what the "condition" actually is: bash doesn't test true/false values, it tests a command's exit code. if runs the command and treats exit code 0 as true, anything else as false. That's why if [ -f file ] works — [ is itself a command that exits 0 when the test passes.
if CONDITION; then
STATEMENTS
fi
if CONDITION; then
STATEMENTS
else
STATEMENTS
fi
Example - check if service is running:
systemctl is-active sshd > /dev/null 2>&1
if [ $? -ne 0 ]; then
sudo systemctl start sshd
else
echo "sshd already running"
fi
Important syntax rules:
- Space after
[and before] - Semicolon before
then(orthenon new line) - End with
fi(if backwards)
One-liner:
if [ -f /etc/passwd ]; then echo "exists"; fi