Javatpoint Logo
Javatpoint Logo

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:

Example 1

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.

Bash Script

Output

  • If we enter the number of quantity as 110, then the condition of 'if statement' evaluates to true and the output looks like:
Bash Else If
  • If we enter the number of quantity as 90 then condition of 'elif statement' evaluates to true, and the output looks like:
Bash Else If
  • If we enter the number of quantity as 100, then no condition will be true. In this case, the block of commands inside the 'else statement' is executed, and the output looks like:
Bash Else If

This is how basic bash else-if works.

Example 2

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.

Bash Script

Note: It should be noted that else block is optional.

Output

If we enter the number of quantity as 100, then the output will look like:

Bash Else If

Try this example by putting different values and check out the results.

Conclusion

In this topic, we have learned about the syntax and usage of Bash else-if statement with the examples.


Next TopicBash Case




Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA