萬盛學電腦網

 萬盛學電腦網 >> Linux教程 >> linux命令find -exec操作的問題

linux命令find -exec操作的問題

    最近有這樣一個需求,刪掉某目錄下的一些文件夾。其實就是名為"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
    可是這種差別為什麼會導致如此明顯的差異呢? 想了想, 悟到了:

copyright © 萬盛學電腦網 all rights reserved