Skip to content
Tutorials Center
My learning

Topics

Linux Command Reference ยท Bash Syntax

Bash if statement

Reference for the Bash if statement: syntax with then, elif, else and fi, how exit status decides the branch, testing commands directly and common mistakes.

The if statement runs a block of commands only when a condition holds. In Bash the condition is a command: if its exit status is 0 the then branch runs, otherwise the shell tries each elif and finally else. There is no boolean type; [ ], [[ ]], (( )), grep -q and any other command can serve as a condition.

Because the test is just a command, you can write if grep -q root /etc/passwd; then directly, without comparing anything.

Terminal
if condition; then
  commands
elif other-condition; then
  commands
else
  commands
fi

Try it

Bash Branching on tests and commands

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Bash Exit status and multi-command conditions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Syntax

Terminal
if list; then list
[ elif list; then list ] ...
[ else list ]
fi
Part Description
if list The condition. The list may hold several commands; the exit status of the last one is used.
then list Runs when the status is 0. Must contain at least one command.
elif list Another condition tried when all earlier ones failed.
else list Runs when no condition succeeded.
fi Ends the statement.

Returns: the exit status of the last command run in the chosen branch, or 0 if no branch ran.

Usage notes

  • then must start a new command: put it on its own line or after a ;. if [ -f x ] then is a syntax error.
  • [ is a command, so it needs spaces: [ -f "$f" ], not [-f "$f"] or [ -f "$f"]. Always quote variables inside [ ]; [[ ]] does not need it.
  • Use [[ ]] for strings and patterns, (( )) for arithmetic, and [ ] when you need to stay POSIX-portable. See test operators and [[ ]].
  • The condition is not limited to a test: if cmd; then checks whether cmd succeeded. Add -q or >/dev/null to keep it quiet.
  • Do not compare $? after a command if you can put the command in the if itself. It is shorter and survives set -e, which does not trigger on a failing if condition.
  • A branch cannot be empty. Use the : builtin when you need a placeholder.
  • Inside [ ], = compares strings and an unquoted < is a redirection. Compare numbers with -eq, -lt and friends, or use (( )).
  • For many branches on one value, case is clearer than a long elif chain.