Possible Duplicate:
Delete all but the most recent X files in bash
I have a script to create incremental backups daily and I need to delete all backups but last 5.
For example, I have this folders:
drwxr-xr-x 4 root root 4096 Oct 29 01:10 2010-10-29 drwxr-xr-x 4 root root 4096 Oct 30 01:10 2010-10-30 drwxr-xr-x 4 root root 4096 Oct 31 01:10 2010-10-31 drwxr-xr-x 4 root root 4096 Nov 1 01:10 2010-11-01 drwxr-xr-x 4 root root 4096 Nov 2 01:10 2010-11-02 drwxr-xr-x 4 root root 4096 Nov 3 01:10 2010-11-03 drwxr-xr-x 4 root root 4096 Nov 4 01:10 2010-11-04 drwxr-xr-x 4 root root 4096 Nov 5 01:10 2010-11-05 drwxr-xr-x 4 root root 4096 Nov 6 01:10 2010-11-06 drwxr-xr-x 4 root root 4096 Nov 7 01:10 2010-11-07 drwxr-xr-x 4 root root 4096 Nov 8 01:10 2010-11-08
And I need to maintain only the last 5 directories and delete the others. After command execute, I need to have only this:
drwxr-xr-x 4 root root 4096 Nov 4 01:10 2010-11-04 drwxr-xr-x 4 root root 4096 Nov 5 01:10 2010-11-05 drwxr-xr-x 4 root root 4096 Nov 6 01:10 2010-11-06 drwxr-xr-x 4 root root 4096 Nov 7 01:10 2010-11-07 drwxr-xr-x 4 root root 4096 Nov 8 01:10 2010-11-08
I don’t need to delete previous to 5 days, I need to delete all except 5 last directories 🙂
Now I’m using:
find /backup/increment -maxdepth 1 -type d -mtime +5 -exec rm -rf {} \;
But I need to improved not based in time 🙂
EDIT: This is an example for a server that do backups all days, but I need an script that delete all folders previous to last 5 because my computer do backups at 00:10 at night, but not all nights the backup is done it, because my computer isn’t working all days, and I need to have always the last 5 backups 🙂
use the
tailcommand to print lines starting with the n th line (Option-n +N):ls -toutputs the current directory sorted by time.tail -n +6takes al lines starting with the 6th line. Quoting with backticks feeds the result of the pipe into thermcommand.OLD SOLUTION, not correct …
use the
headcommand, which prints the first n lines of some output:ls -toutputs the current directory sorted by time.head -n 5takes the first five entries of the previous output. Quoting with backticks feeds the result of the pipe into thermcommand.Please try out first before applying to live data 🙂 …