最近有這樣一個需求,刪掉某目錄下的一些檔案夾。其實就是名為“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 參數指明匹配只發生在目前的目錄,並不深入子目錄, 結果是這個命令沒有報錯,也驗證了之前的猜想。
在此記錄,以備後查。