Shell脚本删除n天以前的目录
我有目录命名为:
2012-12-12 2012-10-12 2012-08-08 如何删除bash shell脚本超过10天的目录?
这将为你recursion的做到这一点:
 find /path/to/base/dir/* -type d -ctime +10 -exec rm -rf {} \; 
说明:
-   find:用于查找文件/目录/链接等的unix命令
-   /path/to/base/dir:开始search的目录。
-   -type d:只find目录
-   -ctime +10:只考虑修改时间超过10天的那些
-  -exec ... \;:find每个这样的结果,执行下面的命令在...
-   rm -rf {}:recursion强制删除目录;{}部分是查找结果从前一部分代入的位置。
或者,使用:
 find /path/to/base/dir/* -type d -ctime +10 | xargs rm -rf 
哪个更有效一些,因为它相当于:
 rm -rf dir1 dir2 dir3 ... 
而不是:
 rm -rf dir1; rm -rf dir2; rm -rf dir3; ... 
 如在-exec方法中。 
  注意:另请参阅下面的@ MarkReed关于使用现代版本find首选用法的评论。 
 例如,如果要删除/path/to/base下的所有子目录 
 /path/to/base/dir1 /path/to/base/dir2 /path/to/base/dir3 
 但是你不想删除root /path/to/base ,你必须添加-mindepth 1和-maxdepth 1选项,这个选项只能访问/path/to/base下的子目录 
  -mindepth 1将匹配的根/path/to/base排除在外。 
  -maxdepth 1只会匹配/path/to/base下的子目录,例如/path/to/base/dir1 , /path/to/base/dir2和/path/to/base/dir3但不会列出子目录这些以recursion的方式。 所以这些例子子目录将不会被列出: 
 /path/to/base/dir1/dir1 /path/to/base/dir2/dir1 /path/to/base/dir3/dir1 
等等。
 因此,要删除大于10天的/path/to/base下的所有子目录; 
 find /path/to/base -mindepth 1 -maxdepth 1 -type d -ctime +10 | xargs rm -rf 
  find支持-delete操作,所以: 
 find /base/dir/* -ctime +10 -delete; 
我认为有一个文件需要更老的10天以上。 没有尝试过,有人可能会在评论中确认。
 这里最有投票的解决scheme是缺less-maxdepth 0所以它会删除它后,每个子目录将调用rm -rf 。 这没有意义,所以我build议: 
 find /base/dir/* -maxdepth 0 -type d -ctime +10 -exec rm -rf {} \; 
  -delete不使用,因为find会抱怨dir不是空的。 相反,它意味着从下到上的-depth和删除。 
我正在努力使用上面提供的脚本和其他一些脚本,尤其是当文件和文件夹名称有换行符或空格时,才能正确使用它。
最后偶然发现了tmpreaper,到目前为止,它已经很好地工作了。
 tmpreaper -t 5d ~/Downloads tmpreaper --protect '*.c' -t 5h ~/my_prg 
原始来源链接
具有像testing这样的function,recursion地检查目录并列出它们。 删除符号链接,文件或目录的能力,以及某种模式的保护模式
要么
 rm -rf `find /path/to/base/dir/* -type d -mtime +10` 
它的更新,更快的版本:
 find /path/to/base/dir/* -mtime +10 -print0 | xargs -0 rm -f