Advanced Conditional Scripting
Nested Conditional Structures
Advanced bash scripting involves creating complex logical structures that handle multiple conditions and scenarios:
#!/bin/bash
system_type=$(uname -s)
kernel_version=$(uname -r)
if [ "$system_type" == "Linux" ]; then
if [[ "$kernel_version" == *"5.15"* ]]; then
echo "Ubuntu 22.04 LTS detected"
if [ -f /etc/ubuntu-release ]; then
echo "Official Ubuntu system confirmed"
fi
fi
fi
Conditional Logic Flow
graph TD
A[Initial Condition] --> B{First Check}
B -->|True| C{Nested Condition}
C -->|True| D{Deeper Condition}
C -->|False| E[Alternative Path]
D -->|True| F[Specific Action]
D -->|False| E
Case Statement Advanced Usage
Case statements provide sophisticated multi-condition evaluation:
#!/bin/bash
read -p "Enter system role: " role
case "$role" in
"developer")
permissions=755
default_shell="/bin/bash"
;;
"admin")
permissions=750
default_shell="/bin/zsh"
;;
"guest")
permissions=700
default_shell="/bin/sh"
;;
*)
permissions=700
default_shell="/bin/false"
;;
esac
echo "Assigned Permissions: $permissions"
echo "Default Shell: $default_shell"
Complex Condition Evaluation Techniques
Technique |
Description |
Example |
Regex Matching |
Pattern-based conditions |
[[ "$string" =~ ^[0-9]+$ ]] |
Compound Conditions |
Multiple condition checks |
[[ condition1 && condition2 ]] |
Parameter Expansion |
Dynamic condition generation |
[[ -n "${variable:-}" ]] |
Advanced Logical Combinations
#!/bin/bash
check_system_resources() {
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 (( $(echo "$cpu_usage > 80.0" | bc -l) )) ||
(( $(echo "$memory_usage > 90.0" | bc -l) )); then
echo "System resources critically high"
return 1
fi
return 0
}
check_system_resources
Advanced conditional scripting enables precise system interaction, dynamic decision-making, and robust error handling in bash environments.