用于删除超过 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 为您调用,传递适合每个 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 {} +