Conditions — Making Decisions in Bash Scripts¶
Conditions allow Bash scripts to make decisions based on user input, command results, file existence, variable values, or system state. Instead of executing every command sequentially, a script can choose different execution paths depending on whether a condition is true or false. Conditional statements are one of the most important features of Bash scripting and are used extensively in automation, DevOps, cloud infrastructure, monitoring, deployment pipelines, and Linux system administration.
Learning Path¶
Course Progress
What You'll Learn¶
After completing this lesson, you'll be able to:
- Understand conditional statements
- Write
if,else, andelifstatements - Compare numbers and strings
- Test files and directories
- Use logical operators
- Check command exit status
- Write nested conditions
- Apply conditions in production scripts
Prerequisites¶
Complete:
- Modules 1–9
- Module 10 Lesson 1 – Variables
Why Learn Conditions?¶
Imagine writing a backup script.
Without conditions:
If /backup doesn't exist, the script fails.
With conditions:
The script behaves intelligently.
What is a Condition?¶
A condition evaluates whether something is:
- True
- False
Based on the result, Bash executes different code.
Example:
Basic if Statement¶
Syntax:
Example:
Output:
if...else¶
Syntax:
Example:
if...elif...else¶
Useful for multiple decisions.
MARKS=75
if [ $MARKS -ge 90 ]
then
echo "Grade A"
elif [ $MARKS -ge 75 ]
then
echo "Grade B"
else
echo "Grade C"
fi
Numeric Comparison Operators¶
| Operator | Meaning |
|---|---|
-eq | Equal |
-ne | Not Equal |
-gt | Greater Than |
-ge | Greater Than or Equal |
-lt | Less Than |
-le | Less Than or Equal |
Example:
String Comparison Operators¶
| Operator | Meaning |
|---|---|
= | Equal |
!= | Not Equal |
-z | Empty String |
-n | Not Empty |
Example:
File Test Operators¶
| Operator | Description |
|---|---|
-f | Regular file exists |
-d | Directory exists |
-e | File or directory exists |
-r | Readable |
-w | Writable |
-x | Executable |
-s | File is not empty |
Example:
Checking Directories¶
Checking Empty Strings¶
Logical AND¶
Using && inside [[ ]].
Logical OR¶
Logical NOT¶
Nested Conditions¶
Checking Command Success¶
Every Linux command returns an exit code.
Example:
A better approach:
Common Commands¶
Check file.
Check directory.
Check equality.
Check string.
Real Production Examples¶
Verify backup directory.
Check configuration file.
Verify root user.
Production Perspective¶
Conditions are widely used in:
- Backup scripts
- Deployment automation
- CI/CD pipelines
- Kubernetes automation
- Monitoring scripts
- Cloud provisioning
- Infrastructure validation
- Security checks
Nearly every production Bash script contains conditional logic.
Hands-on Lab¶
Task 1¶
Check a number.
Task 2¶
Compare strings.
Task 3¶
Check file existence.
Task 4¶
Check directory.
Task 5¶
Use if...else.
Task 6¶
Use logical AND.
Task 7¶
Use elif.
Task 8¶
Check command success.
Command Deep Dive¶
| Command/Operator | Purpose | Production Example |
|---|---|---|
if | Execute conditionally | Automation |
else | Alternate execution | Error handling |
elif | Multiple conditions | Decision making |
-f | File exists | Config validation |
-d | Directory exists | Backup verification |
$? | Previous command status | Deployment validation |
Common Condition Mistakes¶
| Mistake | Solution |
|---|---|
Missing spaces around [ and ] | Add spaces |
Missing fi | Close every if block |
Using = for numeric comparison | Use -eq, -gt, etc. |
| Forgetting quotes around strings | Quote string variables |
| Ignoring command exit codes | Check command success |
Production Troubleshooting Scenario¶
Scenario
A deployment script fails because the configuration file is missing.
Solution:
if [ -f "/etc/myapp/config.yaml" ]
then
echo "Configuration found"
else
echo "Configuration missing"
exit 1
fi
The script exits safely before attempting deployment.
Best Practices¶
- Keep conditions simple and readable.
- Quote string variables.
- Check file existence before using files.
- Validate command success.
- Use descriptive variable names.
- Handle unexpected conditions gracefully.
Common Mistakes¶
❌ Forgetting the closing fi.
✅ Remember to the closing fi.
❌ Using incorrect comparison operators.
✅ Avoid using incorrect comparison operators when a safer approach exists.
❌ Not quoting string variables.
✅ Always quoting string variables.
❌ Ignoring failed commands.
✅ Always review failed commands.
❌ Creating deeply nested conditions instead of simplifying logic.
✅ Prefer simplifying logic rather than creating deeply nested conditions.
Interview Questions¶
Beginner¶
- What is an
ifstatement? - What is the purpose of
else? - What does
-fcheck? - What does
-dcheck?
Intermediate¶
- What is the difference between
=and-eq? - What is the purpose of
elif? - How do you check whether a command succeeded?
- What is the difference between
-zand-n?
Architect Level¶
- How would you design defensive Bash scripts using conditions?
- How would you validate production configuration before deployment?
- Why should production scripts check every critical operation before continuing?
Summary¶
In this lesson, you learned:
- Conditional statements
if,else, andelif- Numeric comparisons
- String comparisons
- File tests
- Logical operators
- Nested conditions
- Command exit status
- Production scripting best practices
Conditions allow Bash scripts to make intelligent decisions based on system state, user input, command results, and file availability. They are fundamental to building reliable, flexible, and production-ready automation.
Key Takeaways¶
- Conditions enable decision-making in Bash scripts.
- Use
if,else, andeliffor branching logic. - Use appropriate operators for numeric, string, and file comparisons.
- Check command success before proceeding.
- Quote string variables to avoid unexpected behavior.
- Validate inputs and system state before performing critical operations.
What's Next?¶
Loops — Automating Repetitive Tasks in Bash Scripts
You'll explore:
forloopswhileloopsuntilloops- Loop control statements (
breakandcontinue) - Iterating through files and directories
- Reading files line by line
- Production automation examples
By the end of the lesson, you'll be able to automate repetitive tasks efficiently using loops, making your Bash scripts more powerful and scalable.