首页 > 系统 > Linux > 正文

linux命令find -exec操作的问题

2020-10-14 22:38:23
字体:
来源:转载
供稿:网友

    最近有这样一个需求,删掉某目录下的一些文件夹。其实就是名为"CVS"的文件夹,用过CVS的人都知道,CVS会在目录的每一级建立一个名为CVS的文件夹,里面放着CVS相关信息,我需要将某目录下所有的名为"CVS"的文件夹删掉。在LINUX下其实很简单,使用find命令:
    [plain]
    find . -name CVS -exec rm -rf {} /;
    看似没问题,但却报错了:
    [plain]
    find: `./CVS': No such file or directory
    检查了下,发现其实。/CVS这个文件夹确实存在而且此时已经被删掉了,算是功德圆满但是为什么还报错?
    没办法记得find完成这种功能还有一种写法:
    [plain]
    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
    可是这种差别为什么会导致如此明显的差异呢? 想了想, 悟到了:
(责任编辑:VEVB)

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表