有没有办法找到执行我在shell中定义的函数?

例如:

dosomething () {
  echo "Doing something with $1"
}
find . -exec dosomething {} \;

其结果是:

find: dosomething: No such file or directory

有没有办法让find's -exec看到做某事?


当前回答

因为只有shell知道如何运行shell函数,所以必须运行shell才能运行函数。你还需要用export -f标记你的export函数,否则子shell不会继承它们:

export -f dosomething
find . -exec bash -c 'dosomething "$0"' {} \;

其他回答

find . | while read file; do dosomething "$file"; done

Jac的回答很好,但它有几个容易克服的陷阱:

find . -print0 | while IFS= read -r -d '' file; do dosomething "$file"; done

这将使用null作为分隔符而不是换行符,因此具有换行符的文件名将正常工作。它还使用-r标志来禁用反斜杠转义,如果没有它,文件名中的反斜杠将不起作用。它还清除IFS,以便名称中潜在的尾随空白不会被丢弃。

把函数放在一个单独的文件中,然后get find来执行它。

Shell函数在定义它们的Shell内部;Find永远也看不到他们。

在{}中添加引号,如下所示:

export -f dosomething
find . -exec bash -c 'dosomething "{}"' \;

这将纠正由于find返回的特殊字符而导致的任何错误, 例如文件名中带有圆括号的文件。

我发现最简单的方法如下,一次重复两个命令:

func_one () {
  echo "The first thing with $1"
}

func_two () {
  echo "The second thing with $1"
}

find . -type f | while read file; do func_one $file; func_two $file; done