backup_rotate.sh in Bash
Keep the newest three backups, delete the rest, prove it.
#!/usr/bin/env bash
# backup_rotate: keep the newest three backups of a file, drop the rest
set -euo pipefail
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
cd "$work"
echo "content" > data.txt
# simulate five dated backups
for stamp in 0501 0502 0503 0504 0505; do
cp data.txt "data.txt.2026${stamp}.bak"
done
echo "before:"
ls data.txt.*.bak
# newest three survive; ls sorts names, tail slices the rest away
keep=3
ls data.txt.*.bak | head -n -"$keep" | while IFS= read -r old; do
rm "$old"
echo "removed $old"
done
echo "after:"
ls data.txt.*.bak
echo "$(ls data.txt.*.bak | wc -l) backups kept"
How it works
- Dated
.baknames sort correctly by name alone. head -n -3yields everything except the last three.- The while-read loop removes and reports each casualty.
Keywords and builtins used here
cddodoneechoforinreadsettrapwhile
The run, in numbers
- Lines
- 28
- Characters to type
- 602
- Tokens
- 94
- Three-star pace
- 80 tpm
At the three-star pace of 80 tokens a minute, this run takes about 70 seconds.
Step 2 of 2 in Encore, step 26 of 26 in Language basics.