Bash if else Statment
If-else is the decision making statements in bash scripting similar to any other programming. Where execution of a block of statement is decided based on the result of if condition. If it evaluates a condition to true, then if block code is executed, on the false condition, the else block code is executed, which is optional.
Syntax:
1 2 3 4 5 6 | if [condition] then //if block code else // else block code fi |
basically, there are 4 types of if statements.
- if statement
- if-else statement
- else-if ladder statement
- nested if statement
1. Bash – if Statement Example
This is the basic if condition, where the code block executes based on the result of defined condition. If the result is true the code block will be executed, and if result is false program will bypass the code block.
For example, take input of a number from the user and check if the given number is greater than 10. If the condition evaluates to true print a message on screen else not.
1 2 3 4 5 6 7 8 | #!/bin/bash read -p "Enter numeric value: " myvar if [ $myvar -gt 10 ] then echo "Value is greater than 10" fi |
2. Bash – if-else Statement Example
Using if…else statement, we can also execute a statement if the condition goes false. Here you also define a block of statements with else, which will be executed with the condition goes false.
Using the same script as above. Only if a user-entered value is greater than 10 then print “OK”. If the value equals to 10 or less then print “Not OK”
1 2 3 4 5 6 7 8 9 10 | #!/bin/bash read -p "Enter numeric value: " myvar if [ $myvar -gt 10 ] then echo "OK" else echo "Not OK" fi |
3. Bash – If-elif-else Statement Example
In addition to else-if, we can check for new conditions, if the program goes to else block.
The elif (else if) is used for multiple if conditions. In case one if the condition goes false then check another if conditions. For example, input the marks of a student and check if marks are greater or equal to 80 then print “Very Good”. If marks are less than 80 and greater or equal to 50 then print 50 and so on. Check the below script and execute it on the shell with different-2 inputs.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | #!/bin/bash read -p "Enter your marks: " marks if [ $marks -ge 80 ] then echo "Very Good" elif [ $marks -ge 50 ] then echo "Good" elif [ $marks -ge 33 ] then echo "Just Satisfactory" else echo "Not OK" fi |
4. Bash – Nested if Statement Example
With nested if one condition goes true then only check another condition. For example, take 3 numeric values as input and check the greatest value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | #!/bin/bash read -p "Enter value of i :" i read -p "Enter value of j :" j read -p "Enter value of k :" k if [ $i -gt $j ] then if [ $i -gt $k ] then echo "i is greatest" else echo "k is greatest" fi else if [ $j -gt $k ] then echo "j is greatest" else echo "k is greatest" fi fi |