Bash If Else
In this topic, we will understand how to use if-else statements in Bash scripts to get our automated tasks completed.
Bash if-else statements are used to perform conditional tasks in the sequential flow of execution of statements. Sometimes, we want to process a specific set of statements if a condition is true, and another set of statements if it is false. To perform such type of actions, we can apply the if-else mechanism. We can apply the condition with the ‘if statement’.
Bash If Else Syntax
A syntax of if-else statement in Bash Shell Scripting can be defined as below:
Important Points to Remember
- We can use a set of one or more conditions joined using conditional operators.
- Else block commands includes a set of actions to perform when the condition is false.
- The semi-colon (;) after the conditional expression is a must.
Check out the following examples demonstrating the use of the if-else statement in Bash Script:
Example 1
Following example consists of two different scenarios where in the first if-else statement, the condition is true, and in the second if-else statement, the condition is false.
Output
In the first if-else expression, the condition ( 10 -gt 3 ) is true and so the statement in the if block is executed. Whereas in the other if-else expression, the condition ( 3 -gt 10 ) is false and so the statement in the else block is executed.
Example 2
In this example, we explained how to use multiple conditions with the if-else statement in Bash. We use bash logical operators to join multiple conditions.
Output
Bash If Else Statement in a Single Line
We can write complete ‘if-else statement’ along with the commands in a single line. You need to follow the given rules to use if-else statement in a single line:
- Use a semi-colon (;) at the end of statements in if and else blocks.
- Use spaces as a delimiter to append all the statements.
An example is given below demonstrating how to use if-else statement in a single line:
Example
Output
When we enter a value as 25, then the output will look like:
Bash Nested If Else
Just like nested if statement, the if-else statement can also be used inside another if-else statement. It is called nested if-else in Bash scripting.
Following is an example explaining how to make use of the nested if-else statement in Bash:
Example
Output
If we enter 10 as value, then the output will look like this:
Conclusion
In this topic, we have learned about the syntax and usage of Bash if-else statement with the examples.