从 find 调用函数时的变量范围

Dus*_*yte 3 bash find function variable

在 bash 脚本中,我定义了一个从find. 问题是变量的范围没有扩展到函数。如何从函数访问变量?下面是一个例子:

variable="Filename:"

myfunction() {
    echo $variable $1
}

export -f myfunction

find . -type f -exec bash -c 'myfunction "{}"' \;
Run Code Online (Sandbox Code Playgroud)

这将输出文件名,但没有字符串“文件名:”。

是否有更好的方法来调用函数,find以便为find找到的每个文件调用它,并且仍然定义变量?

Sté*_*las 6

不是你问题的答案,但要这样做:

find . -type f -exec bash -c 'myfunction "{}"' \;
Run Code Online (Sandbox Code Playgroud)

除了它不可移植的事实之外,它也非常危险,因为文件名最终被解释bash为 shell 代码。考虑例如如果有一个文件$(rm -rf ~)在那里调用会发生什么。写下来:

find . -type f -exec bash -c 'myfunction "$1"' find+bash {} \;
Run Code Online (Sandbox Code Playgroud)

或者甚至更好(避免bash每个文件运行一个):

find . -type f -exec bash -c 'for file do
  myfunction "$file"; done' find+bash {} +
Run Code Online (Sandbox Code Playgroud)

现在回答你的问题:

你可以这样做:

{ find . -type f -exec printf '%s\0' {} + | while IFS= read -ru3 -d '' file; do
  myfunction "$file"; done 3<&0 <&4 4<&-; } 4<&0
Run Code Online (Sandbox Code Playgroud)

这样,您就myfunction可以在当前bashshell 中进行调用,因此您无需导出myfunction或运行其他bashshell。

如果您find支持-print0谓词(如 GNU、busybox 和一些 BSDs find),您可以替换-exec printf '%s\0' {} +-print0