Wednesday, March 21, 2012

Deleting Older Backup Files in a Folder in a Linux machine

In one of my tasks, I had to maintain a weekly backup of the database and at the same time, was also asked to clear the backup files that were older than 2 months.

To perform this task i followed the following procedure

1) To perform this kind of task,cronjob( a linux utility ) is needed.
cronjob:cronjob is like a scheduler, that automatically performs the give task, at the specified intervals.
Ex: to perform weekly backup , we write backup script and then supply it to the cronjob, with a schedule of 7 days. cronjob automatically runs the script every 7 days

2)The command for backing up the database is
mysqldump --host=hostname --user=username --password=password dbname > dumpfilename.sql

It is written in perl script as:

#!/bin/sh

#############
# Shell Script to backup the database
#############
#finding todays date and assign to dumpfilename
$dumpfilename=
system("mysqldump --host=hostname --user=username --password=password dbname > $dumpfilename.sql");


3)
To delete older backup files, I used modified time as a parameter to delete the older files.
the command for deleting files that are older that 2 days is

find /home/user/yourpath/ -mtime +2 -type f -exec rm -rf {} \;
Or
rm -f `find ./testfolder -mtime +2 -type f`

perl script for it is:

#!/bin/sh
###############################################
## Shell script for deletion
###############################################
##declaring variables
$A_LOG_PATH=~/opt/yourpath/
$PAST=60
system(" rm -f \`find $A_LOG_PATH -mtime +$PAST -type f\` ");

4)Now these 2 perl files are specified in the crontab with a schdule of 7 days for backup.pl and 60 days for deletebckup.pl

Thus,the task was completed.

0 comments:

Post a Comment