How to use an if statement in Bash
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.
Syntax
The syntax of the if statement is as follows:
if test_conditionthenrun_commandfi
Code example
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
Code explanation
Line 1: We declare a variable bar and assign a value of
200to it.Line 3: The
(( ))syntax in theifstatement is used to evaluate the arithmetic expression. The[ ]syntax will provide the exit code to theifstatement. It returns0if the condition is true. Otherwise, it will return1.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 Syntax
The syntax of the if else statement is as follows:
if test_conditionthenrun_commandelif test_conditionthenrun_commandelserun_commandfi
Code example
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
Code explanation
In the code above:
Lines 2–3: We assign the numeric values to the variable
aandb.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
ais greater thanbusing the-gtoperator. 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