Shell脚本删除早于n天的目录 [英] Shell script to delete directories older than n days

查看:81
本文介绍了Shell脚本删除早于n天的目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目录名为:

2012-12-12
2012-10-12
2012-08-08

如何使用bash shell脚本删除超过10天的目录?

How would I delete the directories that are older than 10 days with a bash shell script?

推荐答案

这将为您递归执行:

find /path/to/base/dir/* -type d -ctime +10 -exec rm -rf {} \;

说明:

  • find:用于查找文件/目录/链接等的unix命令.
  • /path/to/base/dir:开始搜索的目录.
  • -type d:仅查找目录
  • -ctime +10:仅考虑修改时间超过10天的内容
  • -exec ... \;:对于找到的每个这样的结果,在...
  • 中执行以下命令
  • rm -rf {}:递归强制删除目录; {}部分是查找结果从上一部分替代的地方.
  • find: the unix command for finding files / directories / links etc.
  • /path/to/base/dir: the directory to start your search in.
  • -type d: only find directories
  • -ctime +10: only consider the ones with modification time older than 10 days
  • -exec ... \;: for each such result found, do the following command in ...
  • rm -rf {}: recursively force remove the directory; the {} part is where the find result gets substituted into from the previous part.

或者,使用:

find /path/to/base/dir/* -type d -ctime +10 | xargs rm -rf

效率更高一点,因为它相当于:

Which is a bit more efficient, because it amounts to:

rm -rf dir1 dir2 dir3 ...

相对于:

rm -rf dir1; rm -rf dir2; rm -rf dir3; ...

-exec方法一样.

使用find的现代版本,您可以将;替换为+,它将为您执行xargs调用的等效功能,并传递与每个exec系统调用相适应的尽可能多的文件:

With modern versions of find, you can replace the ; with + and it will do the equivalent of the xargs call for you, passing as many files as will fit on each exec system call:

find . -type d -ctime +10 -exec rm -rf {} +

这篇关于Shell脚本删除早于n天的目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆