if runs a command, not an expression
An if statement runs a list of commands after the keyword if, and it uses the exit status of the last command in that list to decide what happens next. Zero selects the then branch. Any other value selects the else branch, if there is one. Any command works as the condition, including a test, a grep, or a program you wrote yourself. The syntax is if, then, optional elif and else clauses, and fi, which is if spelled backward.
if grep -q root /etc/passwd; then
echo "root is listed"
fiRead the condition as a command. The -q option makes grep quiet, so it prints nothing and returns 0 when it finds a match. That is the usual choice inside conditions, because the status is all you need. To invert a condition, put ! in front of it, as in if ! grep -q root /etc/passwd; then.
The condition can also be a pipeline. The exit status of a pipeline is the status of its last command, unless pipefail is set. So if ls | grep -q log tests whether the listing contains a name with log in it. Keep that in mind when you use pipes in conditions, because a failure in an earlier stage can be hidden.
Adding elif and else
The elif keyword adds another condition to test when the earlier ones failed. Conditions are checked in order, and only the first true branch runs. The else branch runs when none of the conditions were true. Order matters, because a broad condition placed first hides the narrow ones that follow it.
score=85
if [ "$score" -ge 90 ]; then
echo A
elif [ "$score" -ge 80 ]; then
echo B
else
echo C
fiThe output for a score of 85 is B. If the test for 80 came before the test for 90, every score of 90 or more would print B, because the broader range would match first. Put the most specific condition first, or write the ranges so that they cannot overlap.
A useful way to read a long if chain is to name each branch in your head before you read its body. The first branch handles the most specific case, the middle branches handle ranges or patterns, and the else branch catches everything else. If you cannot name a branch in a few words, the conditions are probably tangled, and it is worth rewriting them so that each test answers one question.
Every if needs its fi. A missing fi is a syntax error that bash reports at the end of the file, which can point far from the mistake. Indent the blocks, so that an unclosed statement is easy to spot.
Testing with commands and their output
Because the condition is a command, you can test for a result without storing the output. Use grep -q for a quiet match, or test a program by its status. The example below checks whether a program is installed, using the builtin command -v:
if command -v jq >/dev/null 2>&1; then
echo "jq is installed"
fiThe command command -v prints the path of a command, and it prints nothing when the name is absent. Its status tells you which case you are in. The redirection silences both output streams, so the script prints only its own message. This pattern is a common way to check a dependency before a script relies on it.
case matches patterns
The case statement compares one value against a list of patterns. The value follows the word case, and each branch is a pattern followed by a closing parenthesis, the commands, and a double semicolon. The statement ends with esac, which is case spelled backward. Patterns are shell globs, so an asterisk matches any text, a question mark matches one character, and a bracket expression matches a set of characters.
case "$name" in
*.txt|*.md) echo text ;;
*.sh) echo script ;;
*) echo unknown ;;
esacThe vertical bar joins alternative patterns in one branch, so *.txt|*.md covers both extensions. Quote the subject as a habit, as in case "$name", although the subject of case is not split into words. The patterns themselves are not quoted, because their wildcards are the point.
Case is better than a long if chain when you compare one value against many literal or pattern choices. It reads like a table, and it gives you one place to add a new choice. Use if when each condition tests something different, such as a numeric range, a file state, or a combination of checks.
Order and the default branch
Only the first matching pattern runs. After a branch runs, case skips the rest. Put the specific patterns first and the default pattern *) last. A catch-all placed at the top matches every value, and every later branch becomes unreachable.
The default branch works like else, and it is worth always including one. An unexpected value then reaches a visible message instead of falling through silently. For a command-line script, printing usage to standard error and exiting with status 2 is a good default.
Another useful habit is to keep the branch bodies short. When a branch grows past a few lines, move its work into a function and call it from the branch. The case statement then remains a clear table of choices, and each branch reads as one action, which makes the whole script easier to change later.
Hands-on: classify files
The block below writes a classifier with case. Run it with several names and check that each result matches the pattern it should match. Then add a branch for log files, placed before the default.
cat > classify.sh << 'EOF'
case $1 in
*.txt|*.md) echo text ;;
*.sh) echo script ;;
*) echo unknown ;;
esac
EOF
bash classify.sh notes.txt
bash classify.sh deploy.sh
bash classify.sh photo.pngEach run prints one word. The word unknown for photo.png shows the default branch working. In the next unit you will combine this kind of branching with loops, so that one script can process many files at once.