Understanding Basic Control Structures in Bash: if-else
Control structures are essential in any programming language, allowing you to control the flow of your script based on certain conditions. In Bash scripting, the if-else
statement is one of the most fundamental control structures. This article will guide you through the basics of using if-else
in Bash.
What is an if-else
Statement?
An if-else
statement in Bash allows you to execute a block of code if a specified condition is true, and optionally execute another block of code if the condition is false. This helps in making decisions within your script.
Basic Syntax
The basic syntax of an if-else
statement in Bash is as follows:
if [ condition ]; then
# code to execute if condition is true
else
# code to execute if condition is false
fi
Example
#!/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 example, the script checks if the variabbash ifle number
is greater than 5. If the condition is true, it prints “The number is greater than 5.” Otherwise, it prints “The number is not greater than 5.”
Copy example in the file and save it in the folder:
nano if-example.sh
Make the file executable:
chmod +x if-example.sh
Execute the file:
./if-example.sh
Output:
The number is greater than 5.
Conditions
In Bash scripting, you can use a variety of conditions within if-else
statements to compare values and make decisions. Here are some of the most commonly used conditions:
Numeric Comparison
-eq
: Equal to-ne
: Not equal to-lt
: Less than-le
: Less than or equal to-gt
: Greater than-ge
: Greater than or equal to
Example:
number=10
if [ $number -eq 10 ]; then
echo "The number is equal to 10."
fi
String Comparison
=
: Equal to!=
: Not equal to<
: Less than (in ASCII alphabetical order)>
: Greater than (in ASCII alphabetical order)-z
: String is null (has zero length)-n
: String is not null (has non-zero length)
string="hello"
if [ "$string" = "hello" ]; then
echo "The string is hello."
fi
File Conditions
-e
: File exists-f
: File is a regular file-d
: File is a directory-r
: File is readable-w
: File is writable-x
: File is executable
file="/path/to/file"
if [ -e $file ]; then
echo "The file exists."
fi
Logical Operators
&&
: Logical AND||
: Logical OR
number=10
if [ $number -gt 5 ] && [ $number -lt 15 ]; then
echo "The number is between 5 and 15."
fi
Combining Conditions
You can combine multiple conditions using logical operators to create more complex expressions.
number=10
if [ $number -gt 5 ] && [ $number -lt 15 ]; then
echo "The number is between 5 and 15."
else
echo "The number is not between 5 and 15."
fi