在写批量制做docker镜像脚本时,先是将代码目录拷贝到对应的制做镜像的目录中,而后遍历镜像目录执行build,制做镜像,镜像build完成以后,再将代码目录删除,删除代码目录时用到find -exec组合命令,可是却报了:linux
No such file or directory
zzfdeMacBook-Air:temp zzf$ mkdir testaaa zzfdeMacBook-Air:temp zzf$ ls | grep testaaa testaaa zzfdeMacBook-Air:temp zzf$ find . -type d -name "testaaa" -exec rm -r {} \; find: ./testaaa: No such file or directory
再次查找testaaa目录,发现testaaa目录确实被删除了。但为何会报: No such file or directory呢?docker
zzfdeMacBook-Air:temp zzf$ ls testaaa ls: testaaa: No such file or directory
查阅了find的资料后发现,find 默认是递归查找,在执行上面的删除目录的组合命令时, 它会遍历testaaa目录, 实际执行过程以下:bash
-maxdepth levels:指定tests和actions做用的最大目录深度,只能为非负整数。能够简单理解为目录搜索深度,但并不是如此。当前path目录的层次为1,因此若指定-maxdepth 0将得不到任何结果。ui
zzfdeMacBook-Air:temp zzf$ ls -d testaaa testaaa zzfdeMacBook-Air:temp zzf$ zzfdeMacBook-Air:temp zzf$ find . -maxdepth 1 -type d -name "testaaa" -exec rm -r {} \; zzfdeMacBook-Air:temp zzf$ echo $? 0 zzfdeMacBook-Air:temp zzf$ ls -d testaaa ls: testaaa: No such file or directory
-prune: 不进入目录(告诉find,不要在要删除的目录中查找子目录或文件),因此可用于忽略目录,但不会忽略普通文件。没有给定-depth时,老是返回true,若是给定-depth,则直接返回false,因此-delete(隐含了-depth)是不能和-prune一块儿使用的code
zzfdeMacBook-Air:temp zzf$ ls -d testaaa testaaa zzfdeMacBook-Air:temp zzf$ find . -type d -name "testaaa" -prune -exec rm -r {} \; zzfdeMacBook-Air:temp zzf$ echo $? 0 zzfdeMacBook-Air:temp zzf$ ls -d testaaa ls: testaaa: No such file or directory
+ 和 ; 区别:递归
; 是find遍历一次执行一次exec后面的command, 而 + 会拆分批量找到的文件或目录,批次运行命令,因此不会返回错误,并且当查找内容过多时, + 会下降CPU使用率。io
zzfdeMacBook-Air:temp zzf$ ls -d testaaa testaaa zzfdeMacBook-Air:temp zzf$ find . -type d -name "testaaa" -exec rm -r {} + zzfdeMacBook-Air:temp zzf$ echo $? 0 zzfdeMacBook-Air:temp zzf$ ls -d testaaa ls: testaaa: No such file or directory
固然也可使用 | (管道) + xargs 的方式:class
find . -type d -name "testaaa" | xargs rm -r
可是当testaaa并不存在时,执行这个组合命令,会返回一个非0的状态码,并不符合个人场景。test