Bash: Automation – code examples
Backup with a Timestamp
#!/usr/bin/env bash
set -euo pipefail
quelle="${1:?Provide a source folder}"
ziel="${2:-$HOME/backups}"
mkdir -p "$ziel"
archiv="$ziel/$(basename "$quelle")-$(date +%Y%m%d-%H%M%S).tar.gz"
tar -czf "$archiv" -C "$(dirname "$quelle")" "$(basename "$quelle")"
echo "Backup: $archiv"
# delete backups older than 14 days
find "$ziel" -name "*.tar.gz" -mtime +14 -deletetar -czf packs and compresses, -C changes the folder beforehand so that no absolute paths end up in the archive. The timestamp prevents overwriting; find … -delete cleans up old backups.
Command with Retries
retry() {
local versuche=$1; shift
local n=1
until "$@"; do
if (( n >= versuche )); then
echo "Gave up after $n attempts: $*" >&2
return 1
fi
echo "Attempt $n failed, waiting $((n * 2))s ..." >&2
sleep $((n * 2))
n=$((n + 1))
done
}
retry 3 curl -fsS https://example.com/healthGeneric retry function with increasing wait time (backoff): "$@" runs the passed command with its arguments, until repeats until success. curl -fsS fails with an exit code on HTTP errors, without a progress bar.
Parallel Tasks with xargs -P
find . -name "*.log" -print0 \
| xargs -0 -n 1 -P 4 gzip
# -n 1: one file per call -P 4: up to 4 processes at the same timexargs -P N starts N processes in parallel, -0 safely handles NUL-separated names. Much simpler than home-made background jobs with & and wait.
Disk Space Warning
#!/usr/bin/env bash
set -euo pipefail
schwelle="${1:-80}"
belegung=$(df -P / | awk 'NR == 2 { print $5 }' | tr -d '%')
if (( belegung >= schwelle )); then
echo "WARNING: / is $belegung% full" >&2
exit 1
fi
echo "OK: $belegung%"df -P gives portable output, awk picks line 2 / column 5, tr -d removes the percent sign. Exit code 1 signals the error to monitoring (cron/CI).
cron Entries
# crontab -e
SHELL=/bin/bash
PATH=/usr/local/bin:/usr/bin:/bin
0 2 * * * /home/ada/bin/backup.sh /home/ada/projekte >> /home/ada/logs/backup.log 2>&1
*/15 * * * * flock -n /tmp/check.lock /home/ada/bin/check.sh
30 8 * * 1-5 /home/ada/bin/report.shFive time fields (minute, hour, day, month, weekday) plus command. Cron has a minimal environment: use absolute paths, redirect output and set PATH. flock -n prevents overlapping runs (Linux).