Bash scripting skills separate sysadmins who click through GUIs from ones who can fix twenty servers in the time it takes to fix one by hand. You don’t need to master every corner of the language — a handful of patterns cover the vast majority of real automation tasks.
The Essential Skeleton
#!/usr/bin/env bash
set -euo pipefail # exit on error, undefined variable, or pipe failure
THRESHOLD=90
ALERT_EMAIL="admin@example.com"
usage_pct=$(df / | awk 'NR==2 {print $5}' | tr -d '%')
if (( usage_pct >= THRESHOLD )); then
echo "WARNING: root filesystem at ${usage_pct}% usage" | \
mail -s "Disk space alert on $(hostname)" "$ALERT_EMAIL"
exit 1
fi
echo "Disk usage OK: ${usage_pct}%"
set -euo pipefail Is Non-Negotiable
Without it, Bash silently continues past errors — a failed cd followed by a destructive rm -rf * in the wrong directory is the textbook disaster this one line prevents. Every serious script should start with it.
Working with Arrays and Loops
#!/usr/bin/env bash
set -euo pipefail
servers=("web01" "web02" "db01")
for server in "${servers[@]}"; do
echo "Checking $server..."
if ! ssh -o ConnectTimeout=5 "$server" "uptime"; then
echo " -> UNREACHABLE: $server"
fi
done
Functions and Argument Parsing
#!/usr/bin/env bash
set -euo pipefail
log() { echo "[$(date '+%F %T')] $*"; }
backup_dir() {
local src="$1" dest="$2"
log "Backing up $src to $dest"
tar -czf "$dest/backup-$(date +%F).tar.gz" -C "$src" .
}
backup_dir "/etc" "/backups"
These four patterns — strict mode, arrays with loops, functions with local variables, and structured logging — will carry you through the vast majority of real-world sysadmin scripting.