How to Create Conditional Statements in Bash
Conditional statements in Bash allow you to execute different commands based on certain conditions. The most common conditional statements are if
, elif
, and else
. Below, we will explore how to create and use these conditional statements in Bash scripts.
Basic Syntax of the if
Statement
The basic syntax of an if
statement in Bash is as follows:
if [ condition ]; then
# commands to execute if condition is true
fi
In this syntax:
condition
is the expression that is evaluated. If it is true, the commands within thethen
block are executed.- The
fi
keyword marks the end of theif
statement.
Example of an if
Statement
#!/bin/bash
# Check if a number is positive
number=5
if [ $number -gt 0 ]; then
echo "$number is a positive number."
fi
In this example:
- The script checks if the variable
number
is greater than 0. - If the condition is true, it prints that the number is positive.
Using else
with if
You can extend the if
statement with an else
clause to execute commands when the condition is false:
#!/bin/bash
# Check if a number is positive or negative
number=-3
if [ $number -gt 0 ]; then
echo "$number is a positive number."
else
echo "$number is a negative number."
fi
In this example:
- If the condition is false (i.e., the number is not greater than 0), the script prints that the number is negative.
Using elif
for Multiple Conditions
The elif
(else if) statement allows you to check multiple conditions:
#!/bin/bash
# Check if a number is positive, negative, or zero
number=0
if [ $number -gt 0 ]; then
echo "$number is a positive number."
elif [ $number -lt 0 ]; then
echo "$number is a negative number."
else
echo "$number is zero."
fi
In this example:
- The script checks if the number is positive, negative, or zero and prints the appropriate message based on the condition that evaluates to true.
Using Logical Operators
You can also use logical operators to combine multiple conditions:
#!/bin/bash
# Check if a number is between 1 and 10
number=7
if [ $number -ge 1 ] && [ $number -le 10 ]; then
echo "$number is between 1 and 10."
else
echo "$number is outside the range."
fi
In this example:
- The script checks if the number is greater than or equal to 1 and less than or equal to 10 using the logical AND operator (
&&
).
Conclusion
Conditional statements are a powerful feature in Bash scripting that allow you to control the flow of execution based on specific conditions. By using if
, elif
, and else
, you can create scripts that respond dynamically to different inputs and situations. Understanding how to implement these conditional statements will enhance your ability to write effective and efficient Bash scripts.