6. Operators and Expressions#
In Chapter 5, you learned how to create variables and use expansion. Now it’s time to do something with those values: compare them, calculate with them, and make decisions based on them.
Operators are the tools that let you:
Compare: Is this value greater than that?
Calculate: Add, subtract, multiply, divide
Combine: AND, OR logic for complex conditions
Test: Does this file exist? Is this variable set?
Master these, and you’ll be able to write scripts that make intelligent decisions.
What You'll Learn
By the end of this chapter, you will be able to:
✓ Understand different types of operators (arithmetic, comparison, logical) ✓ Perform calculations using arithmetic operators and expressions ✓ Compare values with comparison operators (<, >, ==, !=, etc.) ✓ Combine conditions using logical operators (&&, ||, !) ✓ Test files and variables with test operators ([], [[ ]]) ✓ Use operators effectively in conditional statements ✓ Evaluate complex expressions for decision-making ✓ Avoid common operator mistakes and pitfalls
Chapter Map
Section |
Topic |
Key Concepts |
|---|---|---|
0602 |
Arithmetic Operators |
+, -, *, /, %, $(( )), let |
0603 |
Comparison & Logical |
<, >, ==, -lt, -gt, &&, ||, ! |
0604 |
String & File Tests |
-z, -n, -f, -d, -r, -w, -x |
0605 |
Using Expressions |
Conditionals, brackets, evaluation |
0606 |
Lab: Operator Practice |
Hands-on exercises, real scenarios |
Why This Matters
Operators are the building blocks of decision-making in scripts:
Automation: Scripts make decisions based on data (if load > 80%, restart service)
Validation: Check if inputs are valid before using them
Conditionals: Execute different code based on conditions
Data manipulation: Transform and calculate values
System admin: Monitor thresholds and trigger alerts
Real-world example: A monitoring script uses comparison operators to check if CPU usage is critical, then uses logical operators to determine if an alert should be sent.
Prerequisites
You should already understand:
Variables and variable expansion (Chapter 5)
Basic command syntax and quoting
How to run bash scripts
Basic file operations
If Chapter 5 feels unfamiliar, review it first—this chapter builds directly on those concepts.
Real-World Scenario
Imagine you’re building a backup script that needs to validate conditions:
# Check if backup succeeded
if [ $backup_size -gt 1000000 ]; then
echo "Backup created successfully"
else
echo "ERROR: Backup too small!"
exit 1
fi
# Run backup only if disk has space AND directory is writable
if [ $available_space -gt $needed_space ] && [ -w "$backup_dir" ]; then
tar -czf backup.tar.gz important/
else
echo "Cannot create backup: insufficient space or permission denied"
fi
# Validate user input
if [ -z "$username" ] || [ -z "$password" ]; then
echo "ERROR: Username and password required"
exit 1
fi
Each line uses operators to make intelligent decisions. This chapter teaches you how to write similar logic.
Sample Script: System Health Check
Here’s a complete script that uses operators to evaluate system health:
#!/bin/bash
# Get system metrics
cpu_usage=$(top -bn1 | grep "Cpu(s)" | awk '{print int($2)}')
memory_usage=$(free | grep Mem | awk '{print int($3/$2 * 100)}')
disk_usage=$(df / | tail -1 | awk '{print int($5)}')
# Evaluate conditions using comparison operators
if [ $cpu_usage -gt 80 ]; then
echo "⚠️ WARNING: High CPU usage ($cpu_usage%)"
elif [ $cpu_usage -gt 60 ]; then
echo "⚡ CAUTION: Elevated CPU usage ($cpu_usage%)"
else
echo "✓ CPU healthy ($cpu_usage%)"
fi
# Check memory with comparison operators
if [ $memory_usage -gt 90 ]; then
echo "🔴 CRITICAL: Memory nearly full ($memory_usage%)"
elif [ $memory_usage -gt 75 ]; then
echo "🟡 WARNING: Memory usage high ($memory_usage%)"
else
echo "✓ Memory healthy ($memory_usage%)"
fi
# Check disk space
if [ $disk_usage -gt 95 ]; then
echo "🔴 CRITICAL: Disk almost full ($disk_usage%)"
elif [ $disk_usage -gt 85 ]; then
echo "🟡 WARNING: Disk usage high ($disk_usage%)"
else
echo "✓ Disk healthy ($disk_usage%)"
fi
# Complex condition: alert only if BOTH CPU and Memory are critical
if [ $cpu_usage -gt 80 ] && [ $memory_usage -gt 80 ]; then
echo "🚨 CRITICAL ALERT: CPU and Memory both extremely high!"
fi
# Different behavior based on time of day
hour=$(date +%H)
if [ $hour -ge 22 ] || [ $hour -lt 6 ]; then
if [ $cpu_usage -gt 50 ]; then
echo "⚠️ Unexpected activity during night: CPU at $cpu_usage%"
fi
fi
What this script demonstrates:
Arithmetic operators: Getting numeric values with math
Comparison operators:
-gt(greater than),-lt(less than),-eq(equal)Logical operators:
&&(AND),||(OR) for combining conditionsTest operators:
[ ]for evaluating conditionsPractical application: Real system monitoring
Progression
This chapter is intermediate-level:
Level |
Chapters |
Focus |
|---|---|---|
Beginner |
1-5 |
Fundamentals: shell, files, variables |
Intermediate |
6-7 |
Operators and control flow |
Advanced |
8-15 |
Functions, automation, real systems |
You’ve built the foundation. Now you’re learning to make decisions—the key to intelligent scripts.