In Bash scripting, the if-else statement allows you to make decisions based on conditions and provide an alternative path if the condition is false.
if [ condition ]; then
# commands if condition is true
else
# commands if condition is false
fi
The basic syntax involves using if
followed by the condition in square brackets, the commands to execute if the condition is true, and the else
statement followed by the commands to execute if the condition is false.
Let's look at some examples of how to use if-else statements in Bash:
This script checks if the variable number
is equal to 5 and prints a message if it is, otherwise, it prints a different message.
#!/bin/bash
number=5
if [ $number -eq 5 ]; then
echo "The number is equal to 5."
else
echo "The number is not equal to 5."
fi
In this script, the variable number
is assigned the value 5. The if statement checks if number
is equal to 5 using the -eq
operator, and if true, prints a message. If the condition is false, the else statement prints a different message.
This script checks if the variable string
is equal to 'hello' and prints a message if it is, otherwise, it prints a different message.
#!/bin/bash
string="hello"
if [ "$string" = "hello" ]; then
echo "The string is 'hello'."
else
echo "The string is not 'hello'."
fi
In this script, the variable string
is assigned the value 'hello'. The if statement checks if string
is equal to 'hello' using the =
operator, and if true, prints a message. If the condition is false, the else statement prints a different message.
This script checks if the variable number
is greater than 5 and prints a message if it is, otherwise, it prints a different message.
#!/bin/bash
number=10
if [ $number -gt 5 ]; then
echo "The number is greater than 5."
else
echo "The number is not greater than 5."
fi
In this script, the variable number
is assigned the value 10. The if statement checks if number
is greater than 5 using the -gt
operator, and if true, prints a message. If the condition is false, the else statement prints a different message.
The Bash if-else statement
is a crucial tool for conditional operations in shell scripting. Understanding how to use if-else statements can help you create more dynamic and responsive scripts.