linux 命令 find -exec 操作的问题
最近有这样一个需求,删掉某目录下的一些文件夹。其实就是名为“CVS”的文件夹,用过CVS的人都知道,CVS会在目录的每一级建立一个名为CVS的文件夹,里面放着CVS相关信息,我需要将某目录下所有的名为“CVS”的文件夹删掉。在LINUX下其实很简单,使用find命令:
find . -name CVS -exec rm -rf {} \;
看似没问题,但却报错了:
find: `./CVS': No such file or directory
检查了下,发现其实./CVS这个文件夹确实存在而且此时已经被删掉了,算是功德圆满但是为什么还报错?
没办法记得find完成这种功能还有一种写法:
find . -name CVS -exec rm -rf {} \+
抱着试试的态度,令人意外的是,这种方式成功执行,并未报任何错误,这就叫人疑惑了,没办法只好求助于男人(man) -exec command ;
Execute command; true if 0 status is returned. All following
arguments to find are taken to be arguments to the command until
an argument consisting of ';' is encountered. The string '{}'
is replaced by the current file name being processed everywhere
it occurs in the arguments to the command, not just in arguments
where it is alone, as in some versions of find. Both of these
constructions might need to be escaped (with a '\') or quoted to
protect them from expansion by the shell. See the EXAMPLES sec-
tion for examples of the use of the '-exec' option. The speci-
fied command is run once for each matched file. The command is
executed in the starting directory. There are unavoidable
security problems surrounding use of the -exec option; you
should use the -execdir option instead.
另外一种:
-exec command {} +
This variant of the -exec option runs the specified command on
the selected files, but the command line is built by appending
each selected file name at the end; the total number of invoca-
tions of the command will be much less than the number of
matched files. The command line is built in much the same way
that xargs builds its command lines. Only one instance of '{}'
is allowed within the command. The command is executed in the
starting directory.
也就是说 "-exec" + ";" 为每一个匹配的文件都执行了一次命令,具体到此处就是 rm -rf 命令,而 “-exec” + "+" 只是把匹配的文件名作为命令的参数append到命令后面,即是这样: rm -rf file1 file2 file3
可是这种差别为什么会导致如此明显的差异呢? 想了想, 悟到了:
#1的执行过程应该是这样:
1. 记录并遍历当面层的所有目录和文件,并对比是否匹配。
2. 匹配了名为CVS的文件夹,然后执行了命令 rm -rf ./CVS,
3. 根据之前的记录多所有目录进行递归遍历,此时问题出现,当程序试图进入该层名为“CVS”的目录进行遍历是,发现此目录不存在,所以报错。为什么这个目录没了,哈,在第二步已经被删掉了!
是这样吗: 可以验证:
find . -maxdepth 1 -name CVS -exec rm -rf {} \;
-maxdepth 参数指明匹配只发生在当前目录,并不深入子目录, 结果是这个命令没有报错,也验证了之前的猜想。
在此记录,以备后查。
更多推荐
所有评论(0)