有没有办法找到执行我在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看到做某事?
当前回答
我发现最简单的方法如下,一次重复两个命令:
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
其他回答
在{}中添加引号,如下所示:
export -f dosomething
find . -exec bash -c 'dosomething "{}"' \;
这将纠正由于find返回的特殊字符而导致的任何错误, 例如文件名中带有圆括号的文件。
我会完全避免使用-exec。使用xargs:
find . -name <script/command you're searching for> | xargs bash -c
不直接,不。Find在一个单独的进程中执行,而不是在您的shell中执行。
创建一个shell脚本,完成与函数相同的工作,并找到can -exec。
以这种方式执行函数是不可能的。
为了克服这个问题,你可以把你的函数放在一个shell脚本中,然后从find调用它
# dosomething.sh
dosomething () {
echo "doing something with $1"
}
dosomething $1
现在在find as中使用它:
find . -exec dosomething.sh {} \;
Jac的回答很好,但它有几个容易克服的陷阱:
find . -print0 | while IFS= read -r -d '' file; do dosomething "$file"; done
这将使用null作为分隔符而不是换行符,因此具有换行符的文件名将正常工作。它还使用-r标志来禁用反斜杠转义,如果没有它,文件名中的反斜杠将不起作用。它还清除IFS,以便名称中潜在的尾随空白不会被丢弃。