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.

All Real-World Interview questions Roadmap: Interview readiness

More on Bash scripting tasks