Bash by Example: Conditionals
Using if-else statements and test operators to implement conditional logic, comparing numbers and strings with different operators, checking file existence and permissions, combining conditions with logical AND and OR, and understanding the importance of proper quoting in test expressions.
Code
#!/bin/bash
count=10
# Basic if-else
if [ $count -gt 5 ]; then
echo "Count is greater than 5"
else
echo "Count is small"
fi
# String comparison
name="Alice"
if [ "$name" == "Alice" ]; then
echo "Hello Alice"
fi
# File checks
if [ -e "script.sh" ]; then
echo "File exists"
fi
# Boolean logic (AND / OR)
# Use [[ ... ]] for advanced features
if [[ $count -gt 5 && "$name" == "Alice" ]]; then
echo "Condition met"
fiExplanation
Conditionals in Bash allow you to execute code based on whether a test evaluates to true or false. The basic syntax is if [ condition ]; then ... fi. The brackets [ ... ] are actually a command (synonym for test), so spaces around the brackets are mandatory.
Bash provides a wide range of test operators for different data types:
- Integers:
-eq(equal),-gt(greater than),-lt(less than). - Strings:
==(equal),!=(not equal),-z(empty). - Files:
-e(exists),-f(regular file),-d(directory).
For more advanced logic, Bash offers double brackets [[ ... ]]. This enhanced version supports logical operators like && (AND) and || (OR) directly inside the brackets, and it handles string escaping more safely than single brackets. It is generally recommended for modern scripts.
Code Breakdown
-gt stands for "greater than". Unlike many languages that use > for numbers, Bash uses > for output redirection, so letter-based operators are used for integer comparison."$name" inside single brackets [ ]. If $name were empty or contained spaces, the unquoted version would cause a syntax error.-e checks if a file or directory exists. This is one of many file test operators available in Bash.[[ ... ]] is the modern test command. It allows using && for logical AND directly. In single brackets, you would need to use -a or separate the brackets like [ ... ] && [ ... ].
