shBash

Bash: Automation – code examples

Contents

Backup with a Timestamp

Automation#tar#backup#find#cron
Use case: Regularly back up a project folder as a compressed archive (via cron).
#!/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 -delete

tar -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

Automation#retry#curl#until#backoff
Use case: Try unstable network calls or deployments several times before giving up.
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/health

Generic 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

Automation#xargs#parallel#find
Use case: Process many files (images, logs, archives) simultaneously with several CPU cores.
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 time

xargs -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

Automation#df#awk#cron#monitoring
Use case: Regularly check via cron whether a partition might fill up.
#!/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

Automation#cron#crontab#schedule
Use case: Start scripts automatically daily, hourly or on weekdays.
# 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.sh

Five 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).