Using elif and else
A plain if statement answers a yes-or-no question: run this block, or skip it. Real scripts usually need more. They need a fallback when the test fails, or a choice among three or four possibilities. Bash provides two extra keywords for this: else, which supplies a default branch, and elif, which adds further tests. Together with if, they build a decision chain in which exactly one branch runs.
Understanding the Concept
Think of the whole if statement as a list of questions asked in order. Bash asks the first question. If the answer is yes, it runs that branch and stops asking. If the answer is no, it asks the next question, and so on. When no question is answered with yes, the else branch, if there is one, runs as the final default.
Two consequences follow from this:
- At most one branch of the statement ever runs.
- The order of the tests matters, because the first test that succeeds wins.
Syntax
if CONDITION_1; then
COMMANDS_1
elif CONDITION_2; then
COMMANDS_2
elif CONDITION_3; then
COMMANDS_3
else
DEFAULT_COMMANDS
fi
The parts are:
ifstarts the statement with the first condition, as in lesson 66.elif(short for "else if") adds another condition. You can use as manyelifparts as you need, and each one has its ownthen.elseintroduces the default branch. It has no condition and nothen.fiends the entire statement once, no matter how manyelifparts it has.
Both elif and else are optional. The conditions are ordinary commands, exactly as in a simple if, so everything from lesson 66 about exit statuses still applies: a command that exits with 0 is true and any other status is false.
Basic Example: if and else
The simplest extension is a two-way choice:
n=3
if [ "$n" -gt 5 ]; then
echo "big"
else
echo "small"
fi
Output:
small
The test [ "$n" -gt 5 ] asks whether n is greater than 5. With n=3 it exits with status 1, so Bash skips the then branch and runs the else branch. Exactly one of the two echo commands always runs, which is the guarantee an else provides.
Choosing Among Many Options with elif
When there are more than two outcomes, chain the tests with elif. This script converts numeric scores into letter grades:
for score in 95 83 71 64 20; do
if [ "$score" -ge 90 ]; then
grade=A
elif [ "$score" -ge 80 ]; then
grade=B
elif [ "$score" -ge 70 ]; then
grade=C
elif [ "$score" -ge 60 ]; then
grade=D
else
grade=F
fi
echo "$score -> $grade"
done
Output:
95 -> A
83 -> B
71 -> C
64 -> D
20 -> F
Understanding the Example
Take the score 83:
- Bash tests
83 -ge 90. This is false, so it moves on. - Bash tests
83 -ge 80. This is true, so it assignsgrade=B. - Bash skips every remaining
elifand theelse, and jumps tofi. - The
echoafterfiprints83 -> B.
Notice that the second test does not need to say "80 or more but below 90." By the time Bash reaches an elif, every earlier test has already failed, so the score must be below 90. Each condition only has to describe the lower limit of its range. This keeps the chain short and easy to read.
The score 20 fails every test, so the else branch assigns F. Without the else, grade would keep its value from the previous loop pass, which is a subtle way for a script to produce wrong output. Putting a default in the chain avoids that.
The -ge operator means "greater than or equal to." Lesson 73 covers the numeric comparison operators.
The First Matching Branch Wins
Because Bash stops at the first successful test, tests that overlap are never both reached. Here the second condition can never run:
x=100
if [ "$x" -gt 10 ]; then
echo "over 10"
elif [ "$x" -gt 50 ]; then
echo "over 50 (never reached)"
fi
Output:
over 10
100 is greater than both 10 and 50, but the first test already succeeded, so the elif is never evaluated. The fix is to put the most specific test first: check -gt 50 before -gt 10. When a chain of tests is ordered from narrowest to broadest, or from highest threshold to lowest as in the grade example, each branch can only be reached by the values it is meant for.
Using Commands as Conditions in a Chain
Every condition in the chain can be a different kind of command, not just a comparison. This example checks whether a word appears in a file, and gives different answers depending on why it did not:
printf 'alpha\nbeta\n' > names.txt
word=beta
if grep -q "^$word\$" names.txt; then
echo "$word present"
elif [ -f names.txt ]; then
echo "file exists but no $word"
else
echo "no file"
fi
Output for word=beta:
beta present
Output after changing to word=zeta:
file exists but no zeta
Output after renaming the file so names.txt no longer exists (with the grep error hidden using 2>/dev/null):
no file
The three runs take three different paths through the same statement. The first grep pattern ^$word\$ matches a whole line equal to the word: ^ anchors the start, and the escaped \$ keeps the dollar sign for grep so it anchors the end, while the unescaped $word is replaced by the shell with the value. The elif only runs when the first test failed, which here means either the word was missing or the file could not be read, and the elif separates those cases.
else if Compared with elif
You can nest a whole if statement inside an else branch, written as else followed by a new if:
v=7
if [ "$v" -lt 5 ]; then
echo low
else
if [ "$v" -lt 10 ]; then
echo mid
fi
fi
Output:
mid
This works, but it needs two fi keywords and an extra level of indentation for every test. elif does the same job with one fi, and the chain stays flat:
if [ "$v" -lt 5 ]; then
echo low
elif [ "$v" -lt 10 ]; then
echo mid
fi
Remember the spelling: it is elif, never else if as one construct and never elseif.
The Exit Status of the Whole Statement
As in a simple if, the status of the whole statement is the status of the last command that ran in the branch that was chosen:
if false; then
echo a
else
(exit 4)
fi
echo "status: $?"
Output:
status: 4
The else branch ran (exit 4), which exits its subshell with status 4, and that became the status of the statement. If no branch ran at all (every test failed and there was no else), the status is 0, as lesson 66 explained.
Syntax Errors with elif and else
The rules for else and elif are strict, and the error messages Bash gives are about the token it did not expect, not the real cause.
else and elif must be followed by commands. An empty else is an error:
if true; then echo a; else; fi
s1.sh: line 1: syntax error near unexpected token `;'
s1.sh: line 1: `if true; then echo a; else; fi'
Use : as a do-nothing command if you really need an empty branch.
else must come last. An elif after an else is rejected:
if false; then echo a; else echo b; elif true; then echo c; fi
s2.sh: line 1: syntax error near unexpected token `elif'
s2.sh: line 1: `if false; then echo a; else echo b; elif true; then echo c; fi'
elseif is not a keyword. Bash treats it as the name of a command, so the then after it is unexpected:
if false; then echo a; elseif true; then echo c; fi
s3.sh: line 1: syntax error near unexpected token `then'
s3.sh: line 1: `if false; then echo a; elseif true; then echo c; fi'
Every elif needs its own then. Here the then line is missing:
if false; then echo a
elif true
echo c
fi
s4.sh: line 4: syntax error near unexpected token `fi'
s4.sh: line 4: `fi'
Bash read true and echo c together as the condition of the elif, so the fi arrived before any then.
Writing else if on one line without closing the inner statement leaves the outer one open, which Bash reports at the end of the file:
if false; then echo a; else if true; then echo c; fi
s5.sh: line 2: syntax error: unexpected end of file
The single fi closes the inner if, and the outer if is still waiting for its own fi.
The messages above show the script.sh: line N: prefix that Bash prints for script files. In an interactive terminal the prefix is bash: instead.
Practical Applications
A script that accepts a path and reports what it is makes use of every part of the chain. It handles a missing argument first, then separate kinds of paths, and falls back to an error message:
#!/usr/bin/env bash
path="$1"
if [ -z "$path" ]; then
echo "Usage: $0 PATH"
elif [ -d "$path" ]; then
echo "$path is a directory"
elif [ -f "$path" ]; then
echo "$path is a regular file"
else
echo "$path does not exist"
fi
Saved as kind.sh and run with different arguments:
$ bash kind.sh
Usage: kind.sh PATH
$ bash kind.sh /etc
/etc is a directory
$ bash kind.sh /etc/hostname
/etc/hostname is a regular file
$ bash kind.sh /nothing/here
/nothing/here does not exist
The order is deliberate. The empty-argument test comes first because the later tests would behave oddly with an empty string. The -z test is true when a string has zero length, and -d and -f check for a directory and a regular file. Lesson 71 and 72 explain these file tests. When the number of choices grows large and each one compares the same value, the case statement in lesson 75 is often easier to read than a long elif chain.