The if
statement is one of the most fundamental constructs in Bash scripting, enabling scripts to make decisions based on conditions. Whether you’re a beginner or an experienced developer, understanding how to use the if
statement effectively is essential for writing powerful and flexible shell scripts.
Syntax of the Bash if
Statement
The basic syntax of the if
statement in Bash is:
if [ condition ]; then
# commands to execute if the condition is true
else
# commands to execute if the condition is false
fi
The fi
keyword marks the end of the if
statement. The [ condition ]
part evaluates to either true or false.
Example: Basic if
Statement
Here’s a simple script to check if a file exists:
#!/bin/bash
if [ -f "myfile.txt" ]; then
echo "File exists."
else
echo "File does not exist."
fi
Explanation:
-f
: Tests if “myfile.txt” exists and is a regular file.
Common Conditions in Bash
Here are some commonly used conditions with if
statements:
- File Conditions:
-e file
: Check if the file exists.-d file
: Check if it’s a directory.-r file
: Check if it’s readable.
- String Comparisons:
=
: Check if two strings are equal.!=
: Check if two strings are not equal.-z string
: Check if the string is empty.
- Numeric Comparisons:
-eq
: Equal to.-lt
: Less than.-gt
: Greater than.
Advanced: Using elif
for Multiple Conditions
The elif
keyword allows you to check multiple conditions:
#!/bin/bash
read -p "Enter your age: " age
if [ "$age" -lt 18 ]; then
echo "You are a minor."
elif [ "$age" -ge 18 ] && [ "$age" -lt 65 ]; then
echo "You are an adult."
else
echo "You are a senior."
fi
Nesting and Logical Operators
You can combine conditions using logical operators:
- AND (
&&
) - OR (
||
)
if [ -f "file1.txt" ] && [ -f "file2.txt" ]; then
echo "Both files exist."
fi
Conclusion
The Bash if
statement is a versatile tool that forms the backbone of conditional logic in shell scripting. By mastering its syntax and capabilities, you can write scripts that adapt to various scenarios and automate complex tasks efficiently. Start experimenting with the examples above to elevate your Bash scripting skills!