我确定我漏掉了什么,但我想不出来。给定:
$ 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发布于 2017-02-17 03:58:33
$(basename {})在命令运行之前进行评估。结果是{},因此命令echo $(basename {})变成echo {},并且basename不是针对每个文件运行的。
发布于 2017-02-17 03:56:47
使用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 {}。因此,它只是模仿了在exec中使用find和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.shhttps://stackoverflow.com/questions/42283246
复制相似问题