有没有办法找到执行我在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"' {} \;

其他回答

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

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

对于那些正在寻找一个Bash函数,将在当前目录下的所有文件上执行给定命令的人,我从上面的答案中编译了一个:

toall(){
    find . -type f | while read file; do "$1" "$file"; done
}

注意,它不使用包含空格的文件名(见下文)。

以这个函数为例:

world(){
    sed -i 's_hello_world_g' "$1"
}

假设我想在当前目录的所有文件中将“hello”的所有实例更改为“world”。我会这样做:

toall world

为了确保文件名中的符号安全,请使用:

toall(){
    find . -type f -print0 | while IFS= read -r -d '' file; do "$1" "$file"; done
}

(但是你需要一个处理-print0的find,例如GNU find)。

以这种方式执行函数是不可能的。

为了克服这个问题,你可以把你的函数放在一个shell脚本中,然后从find调用它

# dosomething.sh
dosomething () {
  echo "doing something with $1"
}
dosomething $1

现在在find as中使用它:

find . -exec dosomething.sh {} \;

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

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

批量处理结果

为了提高效率,许多人使用xargs批量处理结果,但这是非常危险的。因此,在find中引入了另一种方法来批量执行结果。

但是请注意,这种方法可能会带来一些警告,例如POSIX-find中要求在命令末尾使用{}。

export -f dosomething
find . -exec bash -c 'for f; do dosomething "$f"; done' _ {} +

Find会将许多结果作为参数传递给一次bash调用,for循环遍历这些参数,执行函数对每个参数执行一些操作。

上面的解决方案从$1开始参数,这就是为什么有_(代表$0)。

逐一处理结果

同样地,我认为公认的最上面的答案应该更正为

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

这不仅更明智,因为参数应该总是以$1开始,而且如果find返回的文件名对shell具有特殊含义,则使用$0可能会导致意外的行为。