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_condition
then
run_command
fi
Syntax

Code example

Let’s look at an example where we determine if the input is an odd or even number.

bar=200
if [ $((bar%2)) -eq 0 ];
then
echo "even";
fi

Code explanation

  • 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 Syntax

The syntax of the if else statement is as follows:

if test_condition
then
run_command
elif test_condition
then
run_command
else
run_command
fi
Syntax for using elif and else keywords

Code example

Let's consider another example that compares two numbers using elif and else keywords:

a=100
b=200
if [ $a == $b ]
then
echo "a is equal to b"
elif [ $a -gt $b ]
then
echo "a is greater than b"
else
echo "a is less than b"
fi

Code explanation

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

Copyright ©2025 Educative, Inc. All rights reserved