Mainak
Mainak

Reputation: 321

Remove older backup from directory using shell command

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

Answers (3)

AlexiusFlavius
AlexiusFlavius

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

vincentr
vincentr

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

Ratish Ravindran
Ratish Ravindran

Reputation: 151

Use

rm -rf `ls -lth backup_*.tar | awk '{print $NF}' | tail -n +4`
  1. ls -lth backup_*.tar will give the sorted list of backup files (newest being at top)
  2. awk '{print $NF}' will print file names and pass it to tail
  3. tail -n +4 , will print file from number 3
  4. At last tail's result is fed to rm to act

Another simplified method

rm -rf `ls -1rt backup_*.tar | tail -n +3`

Upvotes: 0

Related Questions