linuxfind-execrm-r报:Nosuchfileordirectory系统环境Ubuntu16.04.3LTS

在写批量制做docker镜像脚本时,先是将代码目录拷贝到对应的制做镜像的目录中,之后遍历镜像目录执行build,制做镜像,镜像build完成以后,再将代码目录删掉,删掉代码目录时用到find-exec组合命令,然而却报了:

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目录确实被删掉了。但为何会报:Nosuchfileordirectory呢?

zzfdeMacBook-Air:temp zzf$ ls testaaa
ls: testaaa: No such file or directory

查阅了find的资料后发觉,find默认是递归查找,在执行前面的删掉目录的组合命令时,它会遍历testaaa目录,实际执行过程如下:

查询当前目录下的所有目录进行模式匹配"testaaa",匹配成功?成功。执行exec后的命令:rm-rtestaaafind尝试步入到testaaa/目录中,查找目录或文件,并执行exec旁边的命令find没有找到testaaa目录,返回ENOENT(Nosuchfileordirectory)解决方式有好多种,下边只列举常用方法:1.使用find的-maxdepthOPTIONS:

-maxdepthlevels:指定tests和actions作用的最大目录深度,只能为非负整数。可以简单理解为目录搜索深度,但并非这么。当前path目录的层次为1linux find -execlinux格式化命令,所以若指定-maxdepth0将得不到任何结果。

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

2.使用find的-pruneACTIONS:

linux find -exec_linux find -exec_linux find -exec

-prune:不步入目录(告诉findlinux find -exec,不要在要删掉的目录中查找子目录或文件),所以可用于忽视目录,但不会忽视普通文件。没有给定-depth时,总是返回true,倘若给定-depth,则直接返回false,所以-delete(蕴涵了-depth)是不能和-prune一起使用的

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

3.使用find的-deleteACTIONS:

-delete,它蕴涵"-depth"选项

linux find -exec_linux find -exec_linux find -exec

-depth:搜索到目录时,先处理目录中的文件(子目录)常用linux系统,再处理目录本身。对于"-delete"这个action,它蕴涵"-depth"选项

zzfdeMacBook-Air:temp zzf$ ls -d testaaa
testaaa
zzfdeMacBook-Air:temp zzf$ find . -type d -name "testaaa" -delete
zzfdeMacBook-Air:temp zzf$ echo $?
0
zzfdeMacBook-Air:temp zzf$ ls -d testaaa
ls: testaaa: No such file or directory

4.使用+(减号)作为find命令的中止符,而不使用;(分号)

+和;区别:

;是find遍历一次执行一次exec旁边的command,而+会分拆批量找到的文件或目录,批次运行命令,所以不会返回错误,但是当查找内容过多时,+会增加CPU使用率。

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的方法:

find . -type d -name "testaaa" | xargs rm -r

并且当testaaa并不存在时,执行这个组合命令,会返回一个非0的状态码,并不符合我的场景。

本文原创地址:https://www.linuxprobe.com/lmrytxthj.html编辑:刘遄,审核员:暂无