我有这样的东西:
find $1 | grep -E $2 | while read prom; do
if [[ $prom =~ (cmd-given) ]];
then
...
RETURN_PATH=$PWD
cd $WORKING_PATH
...
if [[ -s "stdout-delta" ]] || [[ -s "stderr-delta" ]] || [[ -s "status-delta" ]];
then
RET_ERROR=1
RESULT="FAILED"
else
RESULT="OK"
fi
...
echo "$TEST: $RESULTn" > /dev/stderr
cd $RETURN_PATH
fi
done
我想测试是否在每个有cmd的文件夹中检查空文件x-delta。如果这些文件中有任何一个不是空的,我想写FAILED并将返回代码设置为1。但我想检查所有文件夹,所以我认为我使用变量,将其设置为1,并在结束时检查它是否等于1,退出1,否则退出0。但有一个问题,当我退出循环时,我的变量中没有1。那么我该如何解决这个问题呢?
循环在子进程中运行,因此您必须使用某种形式的IPC与原始进程(shell)进行通信。
最简单的解决方案可能只是将错误消息回显到stdout,并在while循环之后添加一个管道来解析输出。一个简单的grep就足够了。只需确保没有其他命令可以将"FAILED"写入stdout即可。
find $1 | grep -E $2 | while read prom; do
if [[ $prom =~ (cmd-given) ]];
then
...
RETURN_PATH=$PWD
cd $WORKING_PATH
...
if [[ -s "stdout-delta" ]] || [[ -s "stderr-delta" ]] || [[ -s "status-delta" ]];
then
RET_ERROR=1
RESULT="FAILED"
echo $RESULT
else
RESULT="OK"
fi
...
echo "$TEST: $RESULTn" > /dev/stderr
cd $RETURN_PATH
fi
done | grep -q FAILED
[ "$?" == 0 ] && exit 1
编辑:基于临时文件的解决方案:
TMPFILE=$0.tmp
trap "rm -f $TMPFILE; exit 1" 0 1 2 3 13 15
find $1 | grep -E $2 | while read prom; do
if [[ $prom =~ (cmd-given) ]];
then
...
RETURN_PATH=$PWD
cd $WORKING_PATH
...
if [[ -s "stdout-delta" ]] || [[ -s "stderr-delta" ]] || [[ -s "status-delta" ]];
then
RET_ERROR=1
RESULT="FAILED"
echo $RESULT >> $TMPFILE
else
RESULT="OK"
fi
...
echo "$TEST: $RESULTn" > /dev/stderr
cd $RETURN_PATH
fi
done
grep -q FAILED $TMPFILE && rm $TMPFILE && exit 1
rm $TMPFILE && exit 0
编辑2:基于功能的解决方案
process () {
find $1 | grep -E $2 | (cat; echo EXIT_MARKER) | while read prom; do
[[ $prom == "EXIT_MARKER" ]] && exit $EXIT_STATUS
if [[ $prom =~ (cmd-given) ]];
then
...
RETURN_PATH=$PWD
cd $WORKING_PATH
...
if [[ -s "stdout-delta" ]] || [[ -s "stderr-delta" ]] || [[ -s "status-delta" ]];
then
RET_ERROR=1
RESULT="FAILED"
EXIT_STATUS=1
else
RESULT="OK"
fi
...
echo "$TEST: $RESULTn" > /dev/stderr
cd $RETURN_PATH
fi
done
exit 0
}
process $1 $2
exit $?