Bash If-Else Statement With Examples
If-else statements in bash scripting is similar to any other programming languages; it is a method for a program to make decisions.
In if-else
statements, the execution of a block of statement is decided based on the result of the if
condition.
Bash If-Else Statement Syntax
The syntax of the if-else
statement in bash is:
if [condition]
then
//if block code
else
// else block code
fi
If the condition evaluates to true
, the if
block code is executed, and if the condition evaluates to false
then the else
block code is executed.
The else statement and the else code block is optional.
We have to finish the if
statement with the fi
keyword.
Conditional Comparisons
The expression used by the conditional construct must evaluate to either true
or false
. The expression can be a single string or variable.
- less than - denoted by:
$a -lt $b
or$a < $b
- greater than - denoted by:
$a -gt $b
or$a > $b
- less than or equal to - denoted by:
$a -le $b
or$a <= $b
- greater than or equal to - denoted by:
$a -ge $b
or$a >= $b
- equal to - denoted by:
$a -eq $b
or$a == $b
- not equal to - denoted by:
$a -ne $b
or$a != $b
Logical Operators
The expression within the if
statement can also be a logical combination of multiple comparisons.
The logical operators are:
- logical and - denoted by
$a AND $b
or$a && $b
evaluates totrue
when both variables or statements are true. - logical or - denoted by
$a OR $b
or$a || $b
evaluates totrue
when one of the variables or statements are true.
For example:
#!/bin/bash
first_name="John"
last_name="Doe"
if [[ $first_name = "John" && $last_name = "Doe" ]]
then
echo 'hello John Doe'
fi
Bash if Example
The if
statement is just a simple conditional statement. If the condition within the if[]
evaluates to true
then the if
code block is executed.
Example:
#!/bin/bash
read -p "Enter a number: " mynumber
if [ $mynumber -gt 10 ]
then
echo "The number you entered is greater than 10"
fi
Bash if-else Example
When the result of the if
condition is false
then the code in the else
block is executed, provided there is one.
For example:
#!/bin/bash
read -p "Enter a number: " mynumber
if [ $mynumber -gt 10 ]
then
echo "The number you entered is greater than 10"
else
echo "The number you entered is less than 10"
fi
Bash if-elif-else Example
The elif
(else if) is used when there are multiple if
conditions.
For example:
#!/bin/bash
read -p "Enter your exam grade: " grade
if [ $grade -ge 80 ]
then
echo "You got A"
elif [ $grade -ge 70 ]
then
echo "You got B"
elif [ $grade -ge 60 ]
then
echo "You got C"
else
echo "Fail"
fi
Bash Nested if Example
We can also have nested if
statements.
For example:
#!/bin/bash
read -p "Enter value of a :" a
read -p "Enter value of b :" b
read -p "Enter value of c :" c
if [ $a -gt $b ]
then
if [ $a -gt $c ]
then
echo "a is greatest"
else
echo "c is greatest"
fi
else
if [ $b -gt $c ]
then
echo "b is greatest"
else
echo "c is greatest"
fi
fi