Deleting oldest files with shell

2019-07-20 06:50发布

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.

标签: shell
2条回答
SAY GOODBYE
2楼-- · 2019-07-20 07:16

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]
查看更多
虎瘦雄心在
3楼-- · 2019-07-20 07:19

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.

查看更多
登录 后发表回答