2

I have a folder /var/backup where a cronjob saves a backup of a database/filesystem. It contains a latest.gz.zip and lots of older dumps which are names timestamp.gz.zip. The folder ist getting bigger and bigger and I would like to create a bash script that does the following:

  • Keep latest.gz.zip
  • Keep the youngest 10 files
  • Delete all other files

Unfortunately, I'm not a good bash scripter so I have no idea where to start. Thanks for your help.

Jens
  • 69,818
  • 15
  • 125
  • 179
Zendler
  • 23
  • 2

2 Answers2

2

In zsh you can do most of it with expansion flags:

files=(*(.Om))
rm $files[1,-9]

Be careful with this command, you can check what matches were made with:

print -rl -- $files[1,-9]
Gilles 'SO- stop being evil'
  • 104,111
  • 38
  • 209
  • 254
Thor
  • 45,082
  • 11
  • 119
  • 130
1

You should learn to use the find command, possibly with xargs, that is something similar to

 find /var/backup -type f -name 'foo' -mtime -20 -delete

or if your find doesn't have -delete:

 find /var/backup -type f -name 'foo' -mtime -20 -print0 | xargs -0 rm -f

Of course you'll need to improve a lot, this is just to give ideas.

Gilles 'SO- stop being evil'
  • 104,111
  • 38
  • 209
  • 254
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
  • 1
    Cool thank you for the hint. I figured out that find /var/backup -mtime +3 -delete (files older than 3 days) is a good solution for me. – Zendler Sep 10 '12 at 13:02
  • 4
    When going for the `xargs` version, you should definitely stick to the form `find . -print0 | xargs -0 cmd`. This ensures proper treatment of filenames containing whitespace. `-print0` tells `find` to emit matches terminated by a NULL character and `-0` tells `xargs` that the NULL character is the delimiter. – Dr. Jan-Philip Gehrcke Sep 10 '12 at 13:58
  • Sticking to this form also minimizes security risks: http://www.gnu.org/software/findutils/manual/html_mono/find.html#Security-Considerations-for-xargs – Dr. Jan-Philip Gehrcke Sep 10 '12 at 14:05