Write a backup script that tars a directory with a timestamp and keeps only the last 7 backups.
IntermediateHands-onBash scripting tasks
Answer
#!/usr/bin/env bash
set -euo pipefail
SRC="/var/www/app"
DEST="/backups"
KEEP=7
TS="$(date +%Y%m%d-%H%M%S)"
mkdir -p "$DEST"
tar -czf "$DEST/app-$TS.tar.gz" -C "$(dirname "$SRC")" "$(basename "$SRC")"
# rotate: delete everything except the newest $KEEP
ls -1t "$DEST"/app-*.tar.gz | tail -n +$((KEEP + 1)) | xargs -r rm -f --
echo "Backup done: app-$TS.tar.gz"
Key trick → tail -n +8 prints from line 8 onwards (everything older than the newest 7), and xargs -r does nothing when the list is empty.
More on Bash scripting tasks
Write the safe header you start every Bash script with, and explain each part.BeginnerWrite a script that alerts when any filesystem is above 80% usage.BeginnerParse an Nginx access log and print the top 10 client IPs by request count.BeginnerWrite a health-check loop that polls a URL until it returns 200, with a timeout.IntermediateParse command-line flags `-e <env>`, `-v` (verbose) and `-h` in a Bash script.IntermediateUse `trap` to clean up a temp directory on exit, even on Ctrl+C or error.Intermediate