Automated Backup Script with Rotation
Intermediate15 min
Create a bash script that performs timestamped backups of files and directories with configurable retention and automatic rotation of old backups.
Prerequisites
- -Bash 4.0+
- -tar and gzip installed
- -Write access to backup destination
Steps
1
Create the backup script
Write a script that creates timestamped compressed backups of a source directory.
$ cat > backup.sh << 'EOF'
#!/usr/bin/env bash
set -euo pipefail
SOURCE_DIR="${1:?'Usage: backup.sh <source> <dest> [retention_days]'}"
BACKUP_DIR="${2:?'Usage: backup.sh <source> <dest> [retention_days]'}"
RETENTION_DAYS="${3:-30}"
TIMESTAMP=$(date +'%Y%m%d_%H%M%S')
BACKUP_NAME="backup_${TIMESTAMP}.tar.gz"
mkdir -p "$BACKUP_DIR"
tar -czf "$BACKUP_DIR/$BACKUP_NAME" -C "$(dirname "$SOURCE_DIR")" "$(basename "$SOURCE_DIR")"
echo "Backup created: $BACKUP_DIR/$BACKUP_NAME"
EOF
chmod +x backup.sh
2
Add backup rotation
Delete backups older than the retention period to prevent disk space exhaustion.
$ cat >> backup.sh << 'EOF'
# Rotate old backups
DELETED=$(find "$BACKUP_DIR" -name 'backup_*.tar.gz' -mtime +"$RETENTION_DAYS" -print -delete | wc -l)
echo "Rotated $DELETED backups older than $RETENTION_DAYS days"
EOF
Always test the find -delete command with -print first to verify which files would be removed before adding -delete.
3
Add backup verification
Verify the backup archive is valid and not corrupted after creation.
$ echo 'tar -tzf "$BACKUP_DIR/$BACKUP_NAME" > /dev/null && echo "Backup verified successfully" || { echo "Backup verification FAILED" >&2; exit 1; }' >> backup.sh
4
Schedule with cron
Add a cron job to run the backup daily at 2 AM.
$ (crontab -l 2>/dev/null; echo '0 2 * * * /path/to/backup.sh /data /backups 30 >> /var/log/backup.log 2>&1') | crontab -
Use >> to append to the log file and 2>&1 to capture both stdout and stderr.
Full Script
FAQ
Discussion
Loading comments...