為什麼要謹慎使用Linux find命令?
- 2019 年 10 月 8 日
- 筆記
最近有朋友提醒我有一個有用的選項來更加謹慎地運行 find 命令,它就是 -ok。除了一個重要的區別之外,它的工作方式與 -exec 相似,它使 find 命令在執行指定的操作之前請求權限。
這有一個例子。如果你使用 find 命令查找文件並刪除它們,你可能使用的是下面的命令:
$ find . -name runme -exec rm {} ;
在當前目錄及其子目錄中中任何名為 「runme」 的文件都將被立即刪除 —— 當然,你要有權限刪除它們。改用 -ok 選項,你會看到類似這樣的東西,但 find 命令將在刪除文件之前會請求權限。回答 y 代表 「yes」 將允許 find 命令繼續並逐個刪除文件。
$ find . -name runme -ok rm {} ;
< rm … ./bin/runme > ?
-execdir 命令也是一個選擇
另一個可以用來修改 find 命令行為,並可能使其更可控的選項是 -execdir 。-exec 會運行指定的任何命令,而 -execdir 則從文件所在的目錄運行指定的命令,而不是在運行find` 命令的目錄運行指定的命令。這是兩個它的例子:
$ pwd
/home/shs
$ find . -name runme -execdir pwd ;
/home/shs/bin
$ find . -name runme -execdir ls ;
ls rm runme
到現在為止還挺好。但要記住的是,-execdir 也會在匹配文件的目錄中執行該命令。如果運行下面的命令,並且目錄包含一個名為 「ls」 的文件,那麼即使該文件沒有執行權限,它也將運行該文件。使用 -exec 或 -execdir 類似於通過 source 來運行命令。
$ find . -name runme -execdir ls ;
Running the /home/shs/bin/ls file
$ find . -name runme -execdir rm {} ;
This is an imposter rm command
$ ls -l bin
total 12
-r-x—— 1 shs shs 25 Oct 13 18:12 ls
-rwxr-x— 1 shs shs 36 Oct 13 18:29 rm
-rw-rw-r– 1 shs shs 28 Oct 13 18:55 runme
$ cat bin/ls
echo Running the $0 file
$ cat bin/rm
echo This is an imposter rm command
-okdir 選項也會請求權限
要更謹慎,可以使用 -okdir 選項。類似 -ok,該選項將請求權限來運行該命令。
$ find . -name runme -okdir rm {} ;
< rm … ./bin/runme > ?
你也可以小心地指定你想用的命令的完整路徑,以避免像上面那樣的冒牌命令出現的任何問題。
$ find . -name runme -execdir /bin/rm {}
find 命令除了默認打印之外還有很多選項,有些可以使你的文件搜索更精確,但謹慎一點總是好的。