This Bash script automatically creates a compressed (.zip) backup of a given source directory and retains only the latest 5 backups by deleting older ones.
- β Zip compression of a source folder
- π Timestamp-based backup naming
- π§Ή Rotation policy: keeps only the latest 5 backups
- π Suitable for automation via cron jobs
./backup.sh <path to your source directory> <path to your backup folder>Example:
./backup.sh /home/ubuntu/devops /home/ubuntu/backupsBackups are stored in the format:
backups_YYYY-MM-DD_HH-MM-SS.zip
e.g., backups_2025-06-20_10-45-30.zip
If there are more than 5 backups in the backup folder, the oldest ones are automatically deleted to retain only the 5 most recent.
- Open crontab:
crontab -e- Add the following line to schedule daily backups at every minute:
* * * * * /bin/bash /path/to/backup.sh /path/to/source /path/to/backup_folder- Save and exit.
- Make sure the script has execution permission:
chmod 764 backup.sh- Ensure
zipis installed:
sudo apt install zip -y # Debian/Ubuntu systems.
βββ backup.sh
βββ backups/
βββ backups_2025-06-20_10-45-30.zip
βββ backups_2025-06-19_10-45-30.zip
βββ ...
Ajay Mall β Automated backup shell script for Linux
