$_ CLI In Depth
Learning progress 0%
lesson scripting exit-codes control-flow

if, elif & case

6 min read Module 13: Scripting Basics & Exit Codes Updated Dec 5, 2026
Cheat Sheet
0:00 / 3:15

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.

BASH3 lines
if grep -q root /etc/passwd; then
  echo "root is listed"
fi

Read 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.

BASH8 lines
score=85
if [ "$score" -ge 90 ]; then
  echo A
elif [ "$score" -ge 80 ]; then
  echo B
else
  echo C
fi

The 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:

BASH3 lines
if command -v jq >/dev/null 2>&1; then
  echo "jq is installed"
fi

The 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.

BASH5 lines
case "$name" in
  *.txt|*.md) echo text ;;
  *.sh) echo script ;;
  *) echo unknown ;;
esac

The 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.

BASH10 lines
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.png

Each 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.

Terminal lab · 2 steps · real Linux in your browser

Branch with if and case

Use a case statement for patterns, then an if chain with a regular expression check.

01
Classify files with case
Create classify.sh in /workspace. It takes one file name and prints one word, chosen with a case statement. It prints text for names that end in .txt or .md, script for .sh, archive for .tar, .tar.gz, or .tgz, and unknown for everything else. Each result goes on its own line, with nothing else printed.
Show hint for step 1
Separate alternative patterns with a vertical bar. Each branch ends with two semicolons, and the catch-all pattern goes last.
02
Grade a score with if and elif
Create grade.sh in /workspace. It takes one score. If there is not exactly one argument, or the argument is not a whole number, it prints usage: grade.sh SCORE to standard error and exits with status 2. Otherwise it prints A for 90 or more, B for 80 to 89, and C for anything lower. Use if, elif, and else for the grades. Check the number with a regular expression test in double brackets, using the =~ operator.
Show hint for step 2
The expression must be ^[0-9]+$ with both anchors. Write the usage line with redirection to standard error, and exit with 2.
Check yourself Question 1 of 4
Concept Check What selects an if branch recall

In an if statement, what decides which branch runs?

Recap & Key Takeaways

An if statement branches on the exit status of any command, and elif and else handle the other cases in the order written.
Put the most specific condition first in an if chain, because the first true branch is the only one that runs.
case matches one value against glob patterns, joins alternatives with a vertical bar, and runs only the first matching branch.
Always include a default branch in case, so that an unexpected value produces a visible result.
Was this lesson helpful? Spot an issue or have a suggestion? Let us know on GitHub.
Report an issue