有没有办法找到执行我在shell中定义的函数?
例如:
dosomething () {
echo "Doing something with $1"
}
find . -exec dosomething {} \;
其结果是:
find: dosomething: No such file or directory
有没有办法让find's -exec看到做某事?
有没有办法找到执行我在shell中定义的函数?
例如:
dosomething () {
echo "Doing something with $1"
}
find . -exec dosomething {} \;
其结果是:
find: dosomething: No such file or directory
有没有办法让find's -exec看到做某事?
当前回答
我会完全避免使用-exec。使用xargs:
find . -name <script/command you're searching for> | xargs bash -c
其他回答
因为只有shell知道如何运行shell函数,所以必须运行shell才能运行函数。你还需要用export -f标记你的export函数,否则子shell不会继承它们:
export -f dosomething
find . -exec bash -c 'dosomething "$0"' {} \;
把函数放在一个单独的文件中,然后get find来执行它。
Shell函数在定义它们的Shell内部;Find永远也看不到他们。
我会完全避免使用-exec。使用xargs:
find . -name <script/command you're searching for> | xargs bash -c
在{}中添加引号,如下所示:
export -f dosomething
find . -exec bash -c 'dosomething "{}"' \;
这将纠正由于find返回的特殊字符而导致的任何错误, 例如文件名中带有圆括号的文件。
以这种方式执行函数是不可能的。
为了克服这个问题,你可以把你的函数放在一个shell脚本中,然后从find调用它
# dosomething.sh
dosomething () {
echo "doing something with $1"
}
dosomething $1
现在在find as中使用它:
find . -exec dosomething.sh {} \;