Advanced Bash scripting techniques for system automation, error handling, and script optimization. Learn professional scripting practices for Linux system administration and DevOps workflows.
Advanced Bash Scripting
Master advanced Bash scripting techniques to create robust, maintainable scripts for system administration and automation tasks.
1. Error Handling and Debugging
#!/bin/bash
set -euo pipefail # Exit on error, undefined vars, pipe failures
# Logging function
log() {
echo "[$(date +"%Y-%m-%d %H:%M:%S")] $*" >&2
}
# Error handling
trap "echo "Error on line $LINENO"; exit 1" ERR
# Function with error checking
backup_directory() {
local source="$1"
local destination="$2"
if [[ ! -d "$source" ]]; then
log "ERROR: Source directory $source does not exist"
return 1
fi
log "Starting backup of $source to $destination"
if tar -czf "$destination" "$source"; then
log "Backup completed successfully"
return 0
else
log "ERROR: Backup failed"
return 1
fi
}
2. Advanced Parameter Handling
#!/bin/bash
# Script with advanced argument parsing
usage() {
cat <&2
usage >&2
exit 1
;;
*)
break
;;
esac
done
# Check required arguments
if [[ $# -lt 2 ]]; then
echo "Error: Missing required arguments" >&2
usage >&2
exit 1
fi
SOURCE="$1"
DESTINATION="$2"
3. Array Processing and Functions
#!/bin/bash
# Advanced array operations
# Associative arrays
declare -A server_configs
server_configs[web]="nginx"
server_configs[db]="postgresql"
server_configs[cache]="redis"
# Process array
for server in "${!server_configs[@]}"; do
service="${server_configs[$server]}"
echo "Configuring $server server with $service"
done
# Function with array parameter
process_files() {
local files=("$@")
local processed_count=0
for file in "${files[@]}"; do
if [[ -f "$file" ]]; then
echo "Processing: $file"
# Process file here
((processed_count++))
else
echo "Warning: $file not found" >&2
fi
done
echo "Processed $processed_count files"
}
# Usage
file_list=("/etc/hosts" "/etc/fstab" "/etc/crontab")
process_files "${file_list[@]}"
4. System Integration Scripts
#!/bin/bash
# System monitoring and alerting script
ALERT_EMAIL="admin@example.com"
LOG_FILE="/var/log/system-monitor.log"
monitor_disk_usage() {
local threshold=80
while IFS= read -r line; do
usage=$(echo "$line" | awk "{print $5}" | sed "s/%//")
mount=$(echo "$line" | awk "{print $6}")
if [[ $usage -gt $threshold ]]; then
message="WARNING: Disk usage on $mount is ${usage}%"
echo "$(date): $message" >> "$LOG_FILE"
echo "$message" | mail -s "Disk Usage Alert" "$ALERT_EMAIL"
fi
done < > "$LOG_FILE"
echo "$message" | mail -s "Service Alert" "$ALERT_EMAIL"
# Attempt to restart service
if systemctl restart "$service"; then
echo "$(date): Successfully restarted $service" >> "$LOG_FILE"
fi
fi
done
}
# Main execution
main() {
echo "$(date): Starting system monitoring" >> "$LOG_FILE"
monitor_disk_usage
monitor_services
echo "$(date): System monitoring completed" >> "$LOG_FILE"
}
main "$@"
Conclusion
Advanced Bash scripting enables creation of robust automation tools for system administration. These techniques provide the foundation for professional script development and maintenance.