-> find .. -name bin -exec for file in {}/* ; do echo $file ; done \;
-bash: syntax error near unexpected token `do'
Run Code Online (Sandbox Code Playgroud)
此命令的正确语法是什么?
要使用多个语句(例如 -loop for)作为 的参数-exec,需要显式调用 shell,例如bash:
find .. -name bin -exec bash -c 'for file in "$1"/* ; do echo "$file" ; done' none {} \;
Run Code Online (Sandbox Code Playgroud)
即使对于包含空格或其他敌对字符的文件名,这也是安全的。
bash -c运作可以使用以下形式的命令调用 bash:
bash -c some_complex_commands arg0 arg1 arg2 ...
Run Code Online (Sandbox Code Playgroud)
在这种情况下,bash 将执行 string 中的任何内容some_complex_commands。这些命令可以使用常用的 shell位置参数。上面命令后的第一个参数被分配给,第二个参数arg0被分配给,第三个参数被分配给,等等。$0$1$2
当执行普通的 shell 脚本时,$0是脚本的名称,$1也是出现在命令行上的第一个参数。为了与这一传统保持一致,该bash -c命令被编写为将文件名({}以 find 的表示法)分配给$1. 由于该脚本没有合理的名称,none因此被指定为占位符$0。