Bash · lesson 27 of 30 · Tools for the NASBack up a folder with a date
tar packs the folder, a test reads the archive, and only the newest three stay.
27-dated-backup.sh Download 27-dated-backup.sh
#!/usr/app/TurboShell/bin/bash
# Packs a folder into backups/NAME-DATE.tar.gz and keeps the newest three
set -euo pipefail
folder=${1:?give a folder}
keep=3
mkdir -p backups
target=backups/$(basename "$folder")-$(date +%Y-%m-%d-%H%M%S).tar.gz
if [[ -e $target ]]; then
echo "there is $target already"
exit 1
fi
trap 'rm -f "$target.part"' EXIT
tar -czf "$target.part" "$folder"
tar -tzf "$target.part" >/dev/null # can the copy be read?
mv "$target.part" "$target"
echo "made $target"
mapfile -t old < <(find backups -name "$(basename "$folder")-*.tar.gz" | sort -r | tail -n +$((keep + 1)))
for file in "${old[@]}"; do
rm "$file"
echo "removed $file"
done
echo "$(find backups -name '*.tar.gz' | wc -l) backups"
Terminal
$ mkdir -p backups; touch backups/photos-2026-01-0{1,2,3}-020000.tar.gz
$ bash 27-dated-backup.sh photos
made backups/photos-2026-11-25-140815.tar.gz
removed backups/photos-2026-01-01-020000.tar.gz
3 backups
$ tar -tzf "$(ls backups/photos-* | tail -n 1)" | sort | head -n 3
photos/
photos/beach.jpg
photos/cat.jpgThe numbers or the date differ on your NAS.
Exercise
Take the number of copies as an option.