Deleting oldest files with shell

2019-07-20 06:54发布

问题:

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.

回答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.



回答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]


标签: shell