Reputation: 321
In my shell script, I am creating a backup of my folder. I am setting this activity by cronjob and the schedule keeps on changing.
It is keeping the backup with timestamp. Like for e.g :
cd /tmp/BACKUP_DIR
backup_06-05-2014.tar
backup_06-08-2014.tar
backup_06-10-2014.tar
What I want, whenever I run the script, it should keep the latest one and the previously taken backup only. And delete the remaining backups.
Like if I run the script now, it should keep
backup_06-10-2014.tar
backup_06-18-2014.tar
And delete all the other one. What rm
command should I use ?
Upvotes: 1
Views: 4758
Reputation: 114
Try as follows:
rm $(ls -1t /tmp/BACKUP_DIR | tail -n +2)
Listing sorted by date names of files with remaining only two newest
Upvotes: 6
Reputation: 41
You could try deleting files older that 7 days using a find command, for example :
find /tmp/BACKUP_DIR -maxdepth 1 -type f -name "backup_*.tar" -mtime +6 -exec rm -f {} \;
Upvotes: 4
Reputation: 151
Use
rm -rf `ls -lth backup_*.tar | awk '{print $NF}' | tail -n +4`
Another simplified method
rm -rf `ls -1rt backup_*.tar | tail -n +3`
Upvotes: 0