如何将“{}”的内容分配给“find --exec”中的shell变量

sim*_*tek 9 bash find

我试图编写一个脚本,循环遍历目录中的每个 xml 文件并运行 make NAME= 其中 NM 是文件名减去.xml,我卡住的地方是将{}占位符分配给变量。作为

find . -iname "*.xml" -exec foo=$(echo {}); gmake NAME=$FOO \;
Run Code Online (Sandbox Code Playgroud)

不起作用,因为没有分配给$FOO.

sim*_*tek 13

在 IRC 上进行了大量搜索后,有人向我指出了以下答案

find . -iname "*.xml" -exec bash -c 'echo "$1"' bash {} \;
Run Code Online (Sandbox Code Playgroud)

或以我的示例为例(删除字符串以防止混淆)

find . -iname "*.xml" -exec bash -c 'gmake NAME="$1"' bash {} \;
Run Code Online (Sandbox Code Playgroud)

它的工作方式是 bash 将参数 after-c作为参数,bash {}需要以便将 的内容{}分配给$1not $0,并bash用于填充$0. 它不仅是一个占位符,因为它的内容$0例如用于错误消息中,因此您不想使用诸如_''

要在每次调用 时处理多个文件bash,您可以执行以下操作:

find . -iname "*.xml" -exec bash -c '
   ret=0
   for file do
       gmake NAME="$file" || ret=$?
   done
   exit "$ret"' bash {} +
Run Code Online (Sandbox Code Playgroud)

那个有一个额外的好处,如果任何gmake调用失败,它将报告 infind的退出状态。

更多信息可以从http://mywiki.wooledge.org/UsingFind#Complex_actions 获取