2017-02-16 15 views
2

私は何かが不足していると確信していますが、私はそれを理解できません。与えられた:

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

どのように次の2つのコマンドが異なる結果を表示しますか?

$ 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 {})は2つのステップで解決されます。basename {}は実際のファイル(平文ファイル名を出力する)のbasename以外は何もないので、echo {}と解釈されます。だから、それはあなたが

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

$としてexecechoファイルをfindを使用する場合、正確な動作を模倣するが、INGのに過ぎない(ベース名は、{})コマンドを実行する前に評価されます。結果は{}なので、コマンドecho $(basename {})はecho {}になり、basenameは各ファイルに対して実行されません。