## 📝 Author
Birat Aryal — birataryal.github.io
Created Date: 2025-06-23
Updated Date: Monday 23rd June 2025 08:14:15
Website - birataryal.com.np
Repository - Birat Aryal
LinkedIn - Birat Aryal
DevSecOps Engineer | System Engineer | Cyber Security Analyst | Network Engineer
🧠 Bash if Conditionals
The if statement in Bash is used to perform conditional execution of commands. It forms the foundation for decision-making in scripts.
📐 Basic Syntax
Bash
if [ condition ]; then
# commands
fi
With else
Bash
if [ condition ]; then
# if-block
else
# else-block
fi
With elif (else-if)
Bash
if [ condition1 ]; then
# commands
elif [ condition2 ]; then
# other commands
else
# fallback
fi
🔎 Common Comparison Operators
Numeric
| Operator | Meaning |
|---|---|
-eq |
equal |
-ne |
not equal |
-lt |
less than |
-le |
less than or equal |
-gt |
greater than |
-ge |
greater than or equal |
String
| Operator | Meaning |
|---|---|
= or == |
equal |
!= |
not equal |
-z |
is empty |
-n |
is not empty |
File
| Operator | Meaning |
|---|---|
-f file |
file exists and is a regular file |
-d dir |
directory exists |
-e path |
file or directory exists |
-r |
readable |
-w |
writable |
-x |
executable |
✅ Examples
1. Numeric Comparison
Bash
#!/bin/bash
num=5
if [ $num -gt 3 ]; then
echo "$num is greater than 3"
fi
2. String Comparison
Bash
#!/bin/bash
name="Birat"
if [ "$name" = "Birat" ]; then
echo "Welcome, $name!"
else
echo "Access denied"
fi
3. Check if File Exists
Bash
#!/bin/bash
if [ -f "/etc/passwd" ]; then
echo "File exists"
else
echo "File not found"
fi
4. Nested if Statement
Bash
#!/bin/bash
num=10
if [ $num -gt 0 ]; then
if [ $num -lt 100 ]; then
echo "$num is between 1 and 99"
fi
fi
5. if with Logical Operators
Bash
#!/bin/bash
age=25
if [ $age -gt 18 ] && [ $age -lt 30 ]; then
echo "Eligible"
fi
Other logic options:
-
&&(AND) -
||(OR) -
!(NOT)
🔁 if in Loops (Example)
Bash
#!/bin/bash
for num in 1 2 3 4 5
do
if [ $num -eq 3 ]; then
echo "Three found!"
else
echo "$num"
fi
done
Tips
Use [[ ... ]] for safer conditions
Bash
if [[ $string == "value" ]]; then
echo "Match"
fi