Wrote this today because i was bored and someone asked for something similar on opensuse.us
Code:
#!/bin/bash
# Written by Crouse 08-29-2006
# Backup directory and gzip and rotate backups to keep 7 days worth.
# This script keeps 7 days worth of backups of whatever directory you wish.
# Notes: To UNZIP the backups use tar -zxvf filname.tgz
# The next two lines can be modified to fit your backup needs.
DIR1="/home/$USER/Documents/HayfieldOrders/"; #This is the directory to backup
BAKUPS="/home/$USER/BACKUPS"; #This is the directory to backup too.
# These lines set date and create the backup dir if not there already.
CURRENT_DATE="$(date +%m.%d.%Y)";
mkdir -p $BAKUPS #make dir if not already there for backup storage
tar -c $DIR1 | gzip > $CURRENT_DATE.tgz # Tars and Gzips the directory
mv $CURRENT_DATE.tgz $BAKUPS/ # moves the backups and removes the temp dir and files.
# The following REMOVES all but the last 6 backups
cd $BAKUPS
for i in `ls -t * | tail +2`; do
ls -t * | tail +8 | xargs rm -f
done
exit 0
You can change the tail +8 to something else if you want to keep more than 7 days worth of backups. This assumes you are running this script daily as a cron job.