Advanced Conditional Logic
Nested Conditional Structures
Advanced bash scripting often requires complex decision-making processes that go beyond simple linear conditions. Nested if statements provide a powerful mechanism for creating intricate logical flows.
#!/bin/bash
## Nested conditional example
if [ -d "/var/log" ]; then
echo "Log directory exists"
if [ -w "/var/log" ]; then
echo "Log directory is writable"
if [ $(du -sm /var/log | cut -f1) -lt 1024 ]; then
echo "Log directory size is manageable"
else
echo "Log directory is too large"
fi
else
echo "Log directory is not writable"
fi
else
echo "Log directory does not exist"
fi
Case Statement for Multiple Conditions
The case
statement offers an elegant alternative to complex nested if
structures:
#!/bin/bash
read -p "Enter system role: " role
case $role in
"web")
echo "Configuring web server settings"
;;
"database")
echo "Preparing database configuration"
;;
"application")
echo "Setting up application server"
;;
*)
echo "Unknown system role"
;;
esac
Conditional Logic Flow
graph TD
A[Start] --> B{Primary Condition}
B -->|True| C{Nested Condition}
B -->|False| G[Alternative Path]
C -->|True| D[Specific Action]
C -->|False| E[Fallback Action]
D --> F[Continue Execution]
E --> F
G --> F
Advanced Condition Evaluation Techniques
Technique |
Description |
Example |
Regex Matching |
Pattern validation |
[[ $input =~ ^[0-9]+$ ]] |
Parameter Expansion |
Conditional substitution |
${variable:-default} |
Arithmetic Evaluation |
Numeric condition checks |
(( x > y )) |
Complex Condition Example
#!/bin/bash
## Advanced condition with multiple checks
check_system_status() {
local cpu_usage=$(top -bn1 | grep "Cpu(s)" | awk '{print $2 + $4}')
local memory_usage=$(free | grep Mem | awk '{print $3/$2 * 100.0}')
if [[ $cpu_usage < 80.0 ]] && [[ $memory_usage < 90.0 ]]; then
echo "System resources are within acceptable range"
return 0
else
echo "System resources are critically high"
return 1
fi
}
check_system_status
The advanced conditional logic demonstrates how bash scripts can implement sophisticated decision-making processes, enabling complex system management and automation tasks.