Bash If Else – Syntax & Examples

Bash If Else

In this Bash Tutorial, we shall learn the syntax and usage of Bash If Else statement with example Bash Scripts.

Bash If Else is kind of an extension to Bash If statement.

Syntax of Bash If Else

Syntax of If Else statement in Bash Shell Scripting is as shown below :

where

[ <condition> ]Similar to Bash If statement, you may provide a single condition or multiple conditions after if keyword.
<commands>Set of commands to be run when the <condition> is true.
<other_commands>Set of commands to be run when the <condition> is false.

 

Example 1 : If Else

In this example, we shall look into two scenarios where in one if-else expression, condition is true and in the other, condition is false.

In the first if-else expression, condition is true and hence the statements in the if block are executed. Whereas in the second if-else expression, condition is false and hence the statements in the else block are executed.

 

Example 2 : Bash If Else – Multiple Conditions

In this example, we shall look into a scenario where there could be multiple conditions.

 

Conclusion

In this tutorial, we have learnt about the syntax and usage of if else statement with example bash scripts.