Practical Messaging Scenarios
System Monitoring and Reporting
Disk Space Monitoring Script
#!/bin/bash
df_output=$(df -h / | awk 'NR==2 {print $5}' | sed 's/%//')
if [ $df_output -gt 80 ]; then
echo -e "\e[31mWarning: Disk space usage above 80%\e[0m" >&2
fi
Network Connectivity Check
ping_result=$(ping -c 4 google.com)
if [ $? -eq 0 ]; then
echo "Network connection: Stable"
else
echo "Network connection: Unstable" >&2
fi
Logging and Notification Scenarios
System Event Logging
log_system_event() {
local message="$1"
echo "$(date '+%Y-%m-%d %H:%M:%S') - $message" >> /var/log/system_events.log
}
log_system_event "LabEx environment initialization complete"
User Interaction Scenarios
Interactive User Prompts
read -p "Enter your name: " username
echo "Welcome, $username to the LabEx Linux environment!"
Error Handling Patterns
Function with Error Messaging
backup_files() {
local source="$1"
local destination="$2"
if [ ! -d "$source" ]; then
echo "Error: Source directory does not exist" >&2
return 1
fi
cp -r "$source" "$destination" || {
echo "Backup failed for $source" >&2
return 1
}
}
Messaging Workflow Patterns
graph TD
A[Start Process] --> B{Validation}
B -->|Pass| C[Execute Task]
B -->|Fail| D[Display Error Message]
C --> E[Log Success]
D --> F[Log Error]
E --> G[End Process]
F --> G
Common Messaging Scenarios
Scenario |
Approach |
Example Command |
User Feedback |
Echo with Color |
echo -e "\e[32mTask Complete\e[0m" |
Error Reporting |
Stderr Redirection |
command 2> error.log |
Silent Execution |
Null Redirection |
command > /dev/null 2>&1 |
Best Practices
- Use meaningful and concise messages
- Implement proper error handling
- Utilize color for visual emphasis
- Log critical system events
- Provide clear user guidance
Conditional Messaging Example
check_system_status() {
local critical_services=("ssh" "nginx" "mysql")
for service in "${critical_services[@]}"; do
systemctl is-active --quiet "$service" || {
echo -e "\e[31mWarning: $service service is not running\e[0m" >&2
}
done
}
Advanced Notification Techniques
Email Alerts
send_alert() {
local message="$1"
echo "$message" | mail -s "System Alert" [email protected]
}
Telegram Notification
send_telegram_alert() {
local message="$1"
curl -s -X POST \
"https://api.telegram.org/bot<YOUR_BOT_TOKEN>/sendMessage" \
-d "chat_id=<CHAT_ID>&text=$message"
}