The if
statement in Bash allows us to execute the Bash commands based on certain conditions. The if
statement consists of the if
keyword, then
keyword, and fi
keyword at the end of the statement. The command is executed if the condition evaluates to true.
The syntax of the if
statement is as follows:
if test_conditionthenrun_commandfi
Let’s look at an example where we determine if the input is an odd or even number.
bar=200if [ $((bar%2)) -eq 0 ];thenecho "even";fi
Line 1: We declare a variable bar and assign a value of 200
to it.
Line 3: The (( ))
syntax in the if
statement is used to evaluate the arithmetic expression. The [ ]
syntax will provide the exit code to the if
statement. It returns 0
if the condition is true. Otherwise, it will return 1
.
Line 5: If the condition is true, then we print even
.
The if
condition can also be used to check multiple conditions using the elif
and else
keywords. The elif
keyword is used when we need to check more than one expression. The else
keyword is to perform a default operation when none of the conditions match.
If
else
SyntaxThe syntax of the if
else
statement is as follows:
if test_conditionthenrun_commandelif test_conditionthenrun_commandelserun_commandfi
Let's consider another example that compares two numbers using elif
and else
keywords:
a=100b=200if [ $a == $b ]thenecho "a is equal to b"elif [ $a -gt $b ]thenecho "a is greater than b"elseecho "a is less than b"fi
In the code above:
Lines 2–3: We assign the numeric values to the variable a
and b
.
Lines 5–7: We check if the numbers are equal. If yes, we print a string on the terminal.
Lines 8–10: We check if a
is greater than b
using the -gt
operator. If yes, we print a string on the terminal.
Lines 11–13: If none of the above conditions matches, we print a is less than b
.
Free Resources