Bash Else If
In this topic, we will understand how to use else-if (elif) statements in Bash scripts to get our automated tasks completed.
Bash else-if statement is used for multiple conditions. It is just like an addition to Bash if-else statement. In Bash elif, there can be several elif blocks with a boolean expression for each one of them. In the case of the first 'if statement', if a condition goes false, then the second 'if condition' is checked.
Syntax of Bash Else If (elif)
The syntax of else-if statement in Bash shell scripting can be defined as:
Just like if-else, we can use a set of one or more conditions joined using conditional operators. The set of commands are executed when the condition is true. If there is no true condition, then the block of commands inside the 'else statement' is executed.
Following are some examples demonstrating the usage of the else-if statement:
Following example consists of two different scenarios wherein the first else-if statement, the condition is true, and in the second else-if statement, the condition is false.
This is how basic bash else-if works.
This example is demonstrating how to use multiple conditions with the else-if statement in Bash. We use bash logical operators to join multiple conditions.
Note: It should be noted that else block is optional.
If we enter the number of quantity as 100, then the output will look like:
Try this example by putting different values and check out the results.
In this topic, we have learned about the syntax and usage of Bash else-if statement with the examples.