Real-World Loop Applications
System Administration and Automation Scenarios
Bash loops provide powerful mechanisms for automating complex system tasks, enabling efficient file processing, system monitoring, and batch operations.
File Management and Bulk Processing
#!/bin/bash
backup_dir="/home/user/backups"
mkdir -p "$backup_dir"
for log_file in /var/log/*.log; do
timestamp=$(date +"%Y%m%d_%H%M%S")
cp "$log_file" "$backup_dir/$(basename "$log_file")_$timestamp"
done
This script demonstrates automatic log file backup with timestamped copies.
Batch System Resource Monitoring
#!/bin/bash
threshold=80
for process in $(ps aux | awk '{print $2}'); do
cpu_usage=$(ps -p "$process" -o %cpu | tail -n 1 | tr -d ' ')
if (( $(echo "$cpu_usage > $threshold" | bc -l) )); then
echo "High CPU Process: $process (${cpu_usage}%)"
fi
done
Automated process monitoring for identifying resource-intensive tasks.
Network Connectivity Checking
#!/bin/bash
servers=("google.com" "github.com" "stackoverflow.com")
for server in "${servers[@]}"; do
if ping -c 4 "$server" &> /dev/null; then
echo "$server: Online"
else
echo "$server: Offline"
fi
done
Batch network connectivity verification across multiple servers.
Automation Workflow Patterns
Scenario |
Loop Utility |
Key Benefits |
Log Rotation |
File Processing |
Automated backup |
Resource Monitoring |
System Check |
Performance tracking |
Bulk Operations |
Parallel Processing |
Efficiency |
Workflow Visualization
flowchart TD
A[Start Automation Script] --> B{Iterate Through Resources}
B --> C[Perform Action]
C --> D{Condition Met?}
D --> |Yes| E[Log/Report]
D --> |No| F[Skip/Continue]
E --> B
B --> G[Complete Workflow]
Bash loops transform complex system tasks into streamlined, repeatable automation processes across Linux environments.