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

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

问题描述

我的目录命名为:

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 方法中一样.

as in the -exec method.

使用现代版本的 find,您可以将 ; 替换为 + 并且它会执行与 xargs<等效的操作/code> 为您调用,传递适合每个 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 {} +

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

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