每个参数传递给find

时间:2015-06-23 19:52:13

标签: linux bash shell

我正在编写一个快速脚本来列出目录中的所有文件,在每个文件上运行一个函数,然后打印出状态代码。现在我想要的状态代码是整个事务,而不是最后执行的表达式。例如......

find ./ -maxdepth 1 -name \*.txt -exec my_function {} \;

我们说我的目录中有以下文件file1.txtfile2.txtfile3.txt。当file1.txt传递给-exec时,其状态代码为1,但调用file2.txtfile3.txt会返回0。当我在结束时调用echo $?时,尽管0上的呼叫返回file1.txt,但最后一个表达式会返回1。我想要的是一个状态代码,如果任何表达式在上面的脚本中返回非零值,就像file1.txt所描述的那样,它是非零的。我该怎么做呢?

4 个答案:

答案 0 :(得分:1)

我会建议这样的事情:

status=0
while IFS= read -d '' -r file; do
   my_function "$file"
   ((status |= $?))
done < <(find . -maxdepth 1 -name '*.txt' -print0)

echo "status=$status"

如果来自status=1的任何现有状态为1,则会打印my_function

答案 1 :(得分:0)

find . -maxdepth 1 -name \*.txt  -print0 | xargs -r0 -I {} sh -c "echo {}; echo $?;"

根据lcd047收到的建议,为避免名称中包含"的问题,更好的解决方案是

find . -maxdepth 1 -name \*.txt  -print0 | xargs -r0 -I {} sh -c 'printf "%s\n" "$1"; echo $?' sh {} \;

答案 2 :(得分:0)

您可以执行以下操作(使用GNU查找测试),这将为exec返回非零状态的每个文件打印一行:

find . -maxdepth 1 -name "*.txt" '(' -exec my_function {} \; -o -printf 1\\n ')'

您可以使用-printf打印更具信息性的内容,例如文件名。但无论如何,如果某个文件my_function失败,则只会输出。 (或者如果它打印出来的东西。)

答案 3 :(得分:0)

虽然-exec ... \;仅返回退出状态作为主要的真值,但-exec ... {} +会导致find调用返回非零退出状态(如果任何调用返回非零)退出状态(并且始终作为主要返回true,因为一次调用可能会处理多个文件)。

如果my_function处理多个参数,那么

find ./ -maxdepth 1 -name \*.txt -exec my_function {} \;

将完成这项工作。

如果没有,你可以做

find ./ -maxdepth 1 -name \*.txt -exec sh -c 'r=0; for arg do my_function "$arg" || r=1; done; exit "$r"' sh {} \;