If-else Statement

Learn how to write if statements with several conditional branches.

If-else statement

We considered a simple if statement with a single condition and action. When the condition is met, if performs the action. There are cases when we want to choose one of two possible actions using the condition. The if-else statement solves this task. Here is the statement in the general form:

if CONDITION
then
  ACTION_1
else
  ACTION_2
fi

If we write the if-else statement in one line, it looks like this:

if CONDITION; then ACTION_1; else ACTION_2; fi

Bash executes ACTION_2 if the condition returns the non-zero exit status. The condition is false in this case. Otherwise, Bash executes ACTION_1.

We can extend the if-else statement by the elif blocks. Such a block adds an extra condition and the corresponding action. Bash executes the action if the condition equals true.

Next, we’ll go over an example of an if-else statement. Let’s suppose we want to choose one of three actions depending on the value of a variable. The following if statement does that:

if CONDITION_1
then
  ACTION_1
elif CONDITION_2
then
  ACTION_2
else
  ACTION_3
fi

There is no limit on the number of elif blocks in the statement. We can add as many blocks as we need.

Improving the file comparison

Let’s improve our example of the file comparison. We need to print the message in both cases: when the files match, and when they do not. The following if-else statement does that:

Get hands-on with 1200+ tech skills courses.