If-else Statement
Explore how to use Bash if-else statements to choose actions based on conditions. Learn to write nested and extended if-elif-else structures, improve scripts using the early return pattern to simplify error handling, and understand differences between logical operators and if statements for clearer Bash programming.
We'll cover the following...
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 ...