有没有办法找到执行我在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看到做某事?
当前回答
不直接,不。Find在一个单独的进程中执行,而不是在您的shell中执行。
创建一个shell脚本,完成与函数相同的工作,并找到can -exec。
其他回答
我会完全避免使用-exec。使用xargs:
find . -name <script/command you're searching for> | xargs bash -c
我发现最简单的方法如下,一次重复两个命令:
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
以这种方式执行函数是不可能的。
为了克服这个问题,你可以把你的函数放在一个shell脚本中,然后从find调用它
# dosomething.sh
dosomething () {
echo "doing something with $1"
}
dosomething $1
现在在find as中使用它:
find . -exec dosomething.sh {} \;
在{}中添加引号,如下所示:
export -f dosomething
find . -exec bash -c 'dosomething "{}"' \;
这将纠正由于find返回的特殊字符而导致的任何错误, 例如文件名中带有圆括号的文件。
只是一个关于使用shell的接受答案的警告, 尽管它很好地回答了这个问题,但它可能不是在查找结果上执行某些代码的最有效方式:
这里是bash下的所有解决方案的基准测试, 包括一个简单的for循环的情况: (1465个目录,在一个标准硬盘驱动器上,armv7l GNU/Linux synology_armada38x_ds218j)
dosomething() { echo $1; }
export -f dosomething
time find . -type d -exec bash -c 'dosomething "$0"' {} \;
real 0m16.102s
time while read -d '' filename; do dosomething "${filename}" </dev/null; done < <(find . -type d -print0)
real 0m0.364s
time find . -type d | while read file; do dosomething "$file"; done
real 0m0.340s
time for dir in $(find . -type d); do dosomething $dir; done
real 0m0.337s
“find | while”和“for loop”似乎在速度上最好且相似。