Link to home
Start Free TrialLog in
Avatar of djwburr
djwburr

asked on

Unix script - keep only latest 3 files

I would like to know what parameters to add in order to keep only the last 3 backups for my system. I would like the script to delete the last backup and ensure that only the 3 latest backups are kept. I've included the current script that runs.
#!/usr/bin/ksh
 
# Backup script to do the following:
# 1-Tar the directory /opt/hs-data/raid/cxx_backup/ (cfg save)
# 2-Call the backup script to backup the X and Y databases
 
# Reason for this script is because the XY backup script does not
# save the old backup to a different directory like the Data files
# script.
 
# Setup variables for tar file name and Origination and Destination of backup directories.
STAMP=`date +%Y%m%d-%H%M%S`
DIR_ORI=/opt/hs-data/raid/cxx_backup
DIR_DES=/opt/hs-data/raid/backup/manual_backup
 
# tar old backup file and gzip it in the manual_backup directory.
tar -cvf $DIR_DES/${STAMP}_MANUALBACKUP.tar $DIR_ORI/cfg $DIR_ORI/save
/usr/bin/nice -n -10 /usr/local/bin/gzip ${DIR_DES}/${STAMP}_MANUALBACKUP.tar >/
tmp/zip.log 2>&1

Open in new window

Avatar of dzamfir
dzamfir
Flag of Czechia image

Maybe there is a more easiest way, but you look what I have for you.
You can try to append the following to your script:

ATENTION: Try first on a backup/test directory, to be sure that is working fine for your version of unix.



TB=`expr \`ls *.tar.gz | wc -l\` - 3`   # total number of backups that you currently have minus three
DBKP=`ls -t *.tar.gz | tail -n ${TB}`          # list all backups except the latest three
 
if [ $TB -lt 1 ]             # only if there are more than 3 backups we will use rm command
   then
     break
else
   for BKP in $DBKP
      do
         rm -f $BKP
   done
fi

Open in new window

Avatar of djwburr
djwburr

ASKER

Ok. I'll give that a try and let you know. Thanks
Avatar of Tintin
Here's a version of your script that deletes all the old backups and keeps the 3 newest versions.  I've also, combined the tar/gzip into a single step to save time and disk space.


#!/usr/bin/ksh
STAMP=`date +%Y%m%d-%H%M%S`
DIR_ORI=/opt/hs-data/raid/cxx_backup
DIR_DES=/opt/hs-data/raid/backup/manual_backup
 
tar -cvf - $DIR_ORI/cfg $DIR_ORI/save >$DIR_DES/${STAMP}_MANUALBACKUP.tar.gz
rm -f `ls $DIR_DES/*.tar.gz | sed '1,3d'`

Open in new window

Avatar of djwburr

ASKER

Thanks Tintin.... looks clean, I'll also give that a whirl tonight.
ASKER CERTIFIED SOLUTION
Avatar of Tintin
Tintin

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of djwburr

ASKER

Thanks... I've applied the script changes and will find out tonight. Code looks nice and clean. I will post the results tonight. Thanks very much for your input Tintin!!
Avatar of djwburr

ASKER

Thanks!! Works like a charm