iamarunk iamarunk - 11 months ago 45
Bash Question

Delete all files in a directory matching a time pattern

I am taking one of important folder every day backup by using cron. That folder name it will store with the current date.

Now my requirement is i need to keep only the current day and last two days backup.

i.e I want to keep only:

  • test_2016-11-04.tgz

  • test_2016-11-03.tgz

  • test_2016-11-02.tgz

Remaining folder it has to delete automatically. Please let us know how to do in shell script.

Below is my backup folder structure.

test_2016-10-30.tgz test_2016-11-01.tgz test_2016-11-03.tgz
test_2016-10-31.tgz test_2016-11-02.tgz test_2016-11-04.tgz

Answer Source

you could append end of backup script;

find ./backupFolder -name "test_*.tgz" -mtime +3 -type f -delete

also use this;

ls -1 test_*.tgz | sort -r | awk 'NR > 3 { print }' | xargs -d '\n' rm -f --