In Bash, the if-elif-else
statement is used when you have multiple conditions to evaluate and execute different blocks of code based on those conditions. It allows you to specify multiple alternatives in a sequence and execute the block of code associated with the first condition that evaluates to true. If none of the conditions are true, an optional else
block can be used to execute a default code block. Here’s the basic syntax of an if-elif-else
statement in Bash:
if condition1
then
# code to execute if condition1 is true
elif condition2
then
# code to execute if condition2 is true
else
# code to execute if none of the conditions are true
fi
Each condition
is an expression or command that evaluates to either true or false. The elif
keyword is used for the alternative conditions, and it can be repeated as needed. The else
block is optional and executes if none of the conditions are true.
Here’s an example that demonstrates the usage of an if-elif-else
statement in Bash:
#!/bin/bash
number=10
if ((number < 5))
then
echo "The number is less than 5."
elif ((number > 10))
then
echo "The number is greater than 10."
else
echo "The number is between 5 and 10."
fi
In this example, the if-elif-else
statement checks the value of the number
variable against multiple conditions. If the number is less than 5, it executes the code block following the first then
keyword. If the number is greater than 10, it executes the code block following the second then
keyword. If neither condition is true, it executes the code block following the else
keyword.
When you run this script with the value of number
as 10, it will output:
The number is between 5 and 10.
You can modify the conditions and the associated code blocks inside the if-elif-else
statement based on your specific requirements. The if-elif-else
statement provides a way to handle multiple conditions and execute different code paths accordingly, allowing for more complex decision-making within your Bash scripts.