Mar*_*tus 6 bash find shell-script
为什么我会看到以下内容:
$ find -not -exec bash -c 'foo' \; -quit
bash: foo: command not found
$ echo $?
0
Run Code Online (Sandbox Code Playgroud)
这是我在问题末尾发布的实际脚本的简化版本(如果您真的想知道)。
所以问题是我如何find
使用exec bash -c
一堆查找结果执行 shell并在第一个失败时退出并返回一个非零退出代码,我可以稍后在我的脚本中检查?
* 实际脚本 *
#!/usr/bin/env bash
find path-a path-b path-c \
-iname build.xml -not -exec bash -c 'echo -n "building {} ..." && ant -f {} build && echo "success" || (echo "failure" && exit 1)' \; -quit
RESULT=$?
echo "result was $RESULT"
Run Code Online (Sandbox Code Playgroud)
这可以做到这一点:
#!/bin/bash
RESULT=0
while IFS= read -r -u3 -d $'\0' file; do
echo -n "building $file ..."
ant -f "$file" build &&
echo "success" ||
{ echo "failure" ; RESULT=1 ; break; }
done 3< <(find path-a path-b path-c -print0)
echo "result was $RESULT"
Run Code Online (Sandbox Code Playgroud)
请注意,它find
与bash
循环混合在一起,如下所示。
它不使用$?
而是直接使用变量$RESULT
。
如果一切顺利$RESULT
则为 0,否则为 1。一旦遇到错误,循环就会中断。
它应该能够安全地抵御恶意文件名(因为使用了-print0
)。