"I don't have enough reputation to comment, but the
accepted answer was missing a closing
}
on line 5. After fixing this, the code will throw a
-ne: unary operator expected
error, which points to a problem:
PIPESTATUS
is overwritten by the conditional following the
if
command, so the return value of
process_commands
will never be checked! This is because
[ ${PIPESTATUS[0]} -ne 0 ]
is
equivalent to test ${PIPESTATUS[0]} -ne 0
, which changes
$PIPESTATUS
just like any other command. For example:"
return0 () { return 0;}
return3 () { return 3;}
return0 | return3
echo "PIPESTATUS: ${PIPESTATUS[@]}"
这将按预期返回
PIPESTATUS: 0 3
。但是如果我们引入条件语句会怎样呢?
return0 | return3
if [ ${PIPESTATUS[0]} -ne 0 ]; then
echo "1st command error: ${PIPESTATUS[0]}"
elif [ ${PIPESTATUS[1]} -ne 0 ]; then
echo "2nd command error: ${PIPESTATUS[1]}"
else
echo "PIPESTATUS: ${PIPESTATUS[@]}"
echo "Both return codes = 0."
fi
我们遇到了
[: -ne: unary operator expected
错误,以及这个:
PIPESTATUS: 2
Both return codes = 0.
为了解决这个问题,
$PIPESTATUS
应该被存储在一个不同的数组变量中,像这样:
return0 | return3
TEMP=("${PIPESTATUS[@]}")
echo "TEMP: ${TEMP[@]}"
if [ ${TEMP[0]} -ne 0 ]; then
echo "1st command error: ${TEMP[0]}"
elif [ ${TEMP[1]} -ne 0 ]; then
echo "2nd command error: ${TEMP[1]}"
else
echo "TEMP: ${TEMP[@]}"
echo "All return codes = 0."
fi
这段文本的意思是:“打印出以下内容:”。
TEMP: 0 3
2nd command error: 3
按照预期的意图。
编辑:我已经修复了被接受的答案,但是我会留下这个解释供后人参考。