Table of Content
- Introduction to Conditional Statements in Shell Scripting <a name=”introduction”></a>
- 2. Basic Syntax of If-Else in Shell Script <a name=”basic-syntax”></a>
- 3. Types of If-Else Conditions <a name=”types-of-conditions”></a>
- 4. Conditional Operators in Shell Script <a name=”conditional-operators”></a>
- 5. Advanced Usage of If-Else <a name=”advanced-usage”></a>
- 6. Common Mistakes and Debugging <a name=”common-mistakes”></a>
- 7. Best Practices for Writing If-Else Statements <a name=”best-practices”></a>
- 8. Practical Examples and Use Cases <a name=”practical-examples”></a>
- 9. Conclusion <a name=”conclusion”></a>
-
Introduction to Conditional Statements in Shell Scripting <a name=”introduction”></a>
Conditional statements are fundamental in programming, allowing scripts to make decisions based on certain conditions. In shell scripting, the if-else statement is one of the most commonly used control structures.
- Why Use If-Else?
- Execute different code blocks based on conditions.
- Validate user inputs.
- Check file/directory existence.
- Control script flow dynamically.
2. Basic Syntax of If-Else in Shell Script <a name=”basic-syntax”></a>
The general structure of an if-else statement in Bash is:
sh
if [ condition ]; then
# Code to execute if condition is true
else
# Code to execute if condition is false
fi
Key Notes:
- [ ] or [[ ]] are used for conditions.
- then must be on a new line or separated by ;.
- fi closes the if block.
3. Types of If-Else Conditions <a name=”types-of-conditions”></a>
3.1 Simple If Statement <a name=”simple-if”></a>
Executes code only if the condition is true.
sh
if [ “$var” -eq 10 ]; then
echo “Variable is 10.”
fi
3.2 If-Else Statement <a name=”if-else”></a>
Executes one block if true, another if false.
sh
if [ -f “file.txt” ]; then
echo “File exists.”
else
echo “File not found.”
fi
3.3 If-Elif-Else Statement <a name=”if-elif-else”></a>
Handles multiple conditions.
sh
if [ “$age” -lt 18 ]; then
echo “Child.”
elif [ “$age” -lt 60 ]; then
echo “Adult.”
else
echo “Senior.”
fi
3.4 Nested If-Else <a name=”nested-if-else”></a>
If-else inside another if-else.
sh
if [ -d “folder” ]; then
if [ -w “folder” ]; then
echo “Folder exists and is writable.”
fi
fi
4. Conditional Operators in Shell Script <a name=”conditional-operators”></a>
4.1 Numeric Comparisons
Operator | Description | Example |
-eq | Equal to | [ “$a” -eq “$b” ] |
-ne | Not equal | [ “$a” -ne “$b” ] |
-gt | Greater than | [ “$a” -gt “$b” ] |
-lt | Less than | [ “$a” -lt “$b” ] |
-ge | Greater or equal | [ “$a” -ge “$b” ] |
-le | Less or equal | [ “$a” -le “$b” ] |
4.2 String Comparisons
Operator | Description | Example |
= | Equal strings | [ “$str1” = “$str2” ] |
!= | Not equal strings | [ “$str1” != “$str2” ] |
-z | Empty string | [ -z “$str” ] |
-n | Non-empty string | [ -n “$str” ] |
4.3 File and Directory Checks
Operator | Description | Example |
-e | File exists | [ -e “file.txt” ] |
-f | Regular file (not dir) | [ -f “file.txt” ] |
-d | Directory exists | [ -d “/path” ] |
-r | Readable | [ -r “file.txt” ] |
-w | Writable | [ -w “file.txt” ] |
-x | Executable | [ -x “script.sh” ] |
5. Advanced Usage of If-Else <a name=”advanced-usage”></a>
5.1 Using Logical Operators (AND, OR)
sh
# AND (&&)
if [ “$age” -gt 18 ] && [ “$age” -lt 60 ]; then
echo “Valid working age.”
fi
# OR (||)
if [ “$user” = “admin” ] || [ “$user” = “root” ]; then
echo “Access granted.”
fi
5.2 Ternary-Like Operations
sh
[ “$status” = “success” ] && echo “Done” || echo “Failed”
5.3 Case Statements vs. If-Else
For multiple conditions, case is cleaner:
sh
case “$OS” in
“Linux”) echo “Linux OS” ;;
“Windows”) echo “Windows OS” ;;
*) echo “Unknown OS” ;;
esac
6. Common Mistakes and Debugging <a name=”common-mistakes”></a>
- Missing spaces inside [ ] → [ “$a”==”$b” ] ❌ (correct: [ “$a” = “$b” ])
- Unquoted variables → [ -z $var ] (fails if $var is empty)
- Using = instead of -eq for numbers → [ “$a” = “$b” ] (string comparison)
7. Best Practices for Writing If-Else Statements <a name=”best-practices”></a>
✔ Use [[ ]] for advanced conditions (supports &&, || without -a, -o).
✔ Quote variables to avoid word splitting errors.
✔ Use comments for complex conditions.
✔ Prefer case for multiple fixed patterns.
8. Practical Examples and Use Cases <a name=”practical-examples”></a>
Example 1: User Input Validation
sh
read -p “Enter age: ” age
if [ “$age” -lt 0 ]; then
echo “Invalid age!”
elif [ “$age” -lt 18 ]; then
echo “Minor.”
else
echo “Adult.”
fi
Example 2: File Backup Check
sh
if [ -f “/backup/data.tar.gz” ]; then
echo “Backup exists.”
else
echo “Backup missing. Running backup script…”
tar -czf /backup/data.tar.gz /data
fi
9. Conclusion <a name=”conclusion”></a>
Mastering if-else in shell scripting is crucial for writing dynamic and efficient scripts. By understanding different conditions, operators, and best practices, you can automate tasks effectively.