对 `find` 的结果执行函数 - sh

Execute function on results of `find` - sh

我正在基于 Alpine 在 docker 图像上为 运行 编写 shell 脚本。 shell 是 /bin/sh.

我想做的是为 find 命令的结果执行一个函数。以下适用于我的本地 bashsh shells.

myscript.sh:

#!/bin/sh

function get_tags {
  # do stuff
}


export -f get_tags

# get all YAML files in ./assets/config that have 'FIND' somewhere in the filename
# pass each to the get_tags function
find ./assets/config -type f \( -iname "Find*.yaml" -or -iname "Find*.yml" \) -exec sh -c 'get_tags "[=10=]"' {} \;

当我 运行 它在高山图像上时,但是,我得到以下错误:

./myscript.sh: export: line 31: illegal option -f

还有其他方法吗?

我的问题不是 "what is the difference between sh and bash"。我的问题是:如何在 find 命令的输出上完成 运行ning 函数的任务。

你需要使用bash,像这样:

#!/bin/bash
fun() { echo "fun " ; }
export -f fun
find . -name 'foo' -exec bash -c 'fun ""' -- {} \;

这里的关键是运行bash -c 'fun ""' -- {} \;。您不能直接调用该函数(并向其传递参数)。您需要将其包装到一个最小脚本中,该最小脚本接收 find 传递的参数并将其传递给函数。


注意:我将两个参数传递给 bash -c:字符串 -- 和实际文件名 {}。我按照惯例这样做,因为当脚本由 bash -c 执行时,参数计数从 [=16=] 开始,相反,当 运行 以正常方式执行脚本时,参数计数从 </code> 开始(在文件中,而不是通过 <code>bash -c

bash -c 'fun "[=20=]"' {} \; 可以,但人们可能会认为 [=16=] 是他们从普通脚本中知道的脚本名称。

导出函数是一项 Bash 功能。 Alpine Linux 不附带 Bash。

您可以改为使用 while read 循环来处理结果,因为这是 POSIX 并且适用于所有 shell:

get_tags() {
  echo "Getting tags for "
}

find ./assets/config -type f \( -iname "Find*.yaml" -o -iname "Find*.yml" \) |
    while IFS="" read -r file
    do
      get_tags "$file"
    done