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.
if condition; then commands elif other-condition; then commands else commands fi
Try it
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.
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
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
thenmust start a new command: put it on its own line or after a;.if [ -f x ] thenis 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; thenchecks whethercmdsucceeded. Add-qor>/dev/nullto keep it quiet. - Do not compare
$?after a command if you can put the command in theifitself. It is shorter and survivesset -e, which does not trigger on a failingifcondition. - 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,-ltand friends, or use(( )). - For many branches on one value,
caseis clearer than a longelifchain.