我有这样的事情:
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: $RESULT\n" > /dev/stderr
cd $RETURN_PATH
fi
done
我想测试是否在每个文件夹中都有cmd-given检查空文件x-delta。如果这些文件中的任何一个不为空我想写FAILED并将返回码设置为1.但我想检查所有文件夹,所以我认为我使用变量,将其设置为1,最后检查它是否等于1退出1退出0但是有问题,当我从那个循环中退出时,我的变量中没有1。那我该怎么解决呢?
答案 0 :(得分:2)
循环在子进程中运行,因此您必须使用某种形式的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: $RESULT\n" > /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: $RESULT\n" > /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: $RESULT\n" > /dev/stderr
cd $RETURN_PATH
fi
done
exit 0
}
process $1 $2
exit $?