Bash If Elif And If Else Explained With Examples

How to Use If Statement in Bash Script

The most common and fundamental conditional statement used to take decisions in bash script is the “if” statement. This is mainly used when you need to check if a certain condition is satisfied or not. The syntax to use the if statement in bash is:
In the above syntax, the gets executed only if the is satisfied. For example, if you need to print a message on the console after checking if the user input value is less than 10:
When the above script is executed, the user input value is checked whether it is less than 20 or not. If it is less than 20, then “The value is less than 20.” gets printed as output.

How to Use If Else Statement in Bash Script

So with the if statement, you can perform a certain operation as long as a condition is satisfied. But sometimes you may need to perform an operation if the condition is not satisfied. For this, you can use an “else” conditional statement in combination with the if statement to add more flexibility to your bash script for your Linux distro. The syntax to use the else statement is: For example, to check if the user is eligible to vote or not:

How to Use Else If (Elif) in Bash Script

While the if-else conditional construct is good for checking one condition and executing a task accordingly, what if you need to test multiple conditions? For such a situation, “else if” or “elif” statement comes into play. With elif, you can test multiple conditions and modify your bash script accordingly. The syntax to use the elif statement in bash is:
For example: