2017-02-16 97 views
2

我確定我錯過了一些東西,但我無法弄清楚。鑑於:

$ find -type f 
./hello.txt 
./wow.txt 
./yay.txt 

接下來的兩個命令如何呈現不同的結果?

$ find -type f -exec basename {} \; 
hello.txt 
wow.txt 
yay.txt 

$ find -type f -exec echo $(basename {}) \; 
./hello.txt 
./wow.txt 
./yay.txt 

回答

2

上,使用bash -x調試器展示了這種快速調試,

[的例子是我自己的,只是爲了演示的目的]

bash -xc 'find -type f -name "*.sh" -exec echo $(basename {}) \;' 
++ basename '{}' 
+ find -type f -name '*.sh' -exec echo '{}' ';' 
./1.sh 
./abcd/another_file_1_not_ok.sh 
./abcd/another_file_2_not_ok.sh 
./abcd/another_file_3_not_ok.sh 

而對於剛剛basename {}

bash -xc 'find -type f -name "*.sh" -exec basename {} \;' 
+ find -type f -name '*.sh' -exec basename '{}' ';' 
1.sh 
another_file_1_not_ok.sh 
another_file_2_not_ok.sh 
another_file_3_not_ok.sh 

正如你可以在第一個例子中看到,echo $(basename {})分兩步得到解決,basename {}不過是basename實際文件(輸出純文本文件名),然後將其解釋爲echo {}。所以它只是模仿-ING的確切行爲當您使用findexececho文件作爲

bash -xc 'find -type f -name "*.sh" -exec echo {} \;' 
+ find -type f -name '*.sh' -exec echo '{}' ';' 
./1.sh 
./abcd/another_file_1_not_ok.sh 
./abcd/another_file_2_not_ok.sh 
./abcd/another_file_3_not_ok.sh 
3

$(基名{})在命令運行前評估。結果是{},因此命令echo $(basename {})變爲echo {},並且不會爲每個文件運行基本名稱。