我想在bash中编写一个循环,它执行直到某个命令停止失败(返回非零退出代码),如下所示:
while ! my_command; do # do something done
但是在这个循环中我需要检查my_command返回哪个退出代码,所以我尝试了这个:
while ! my_command; do if [ $? -eq 5 ]; then echo "Error was 5" else echo "Error was not 5" fi # potentially,other code follows... done
但那么特殊变量呢?在循环体内变为0.
明显的解决方案是:
while true; do my_command EC=$? if [ $EC -eq 0 ]; then break fi some_code_dependent_on_exit_code $EC done
如何检查循环体内my_command(在循环头中调用)的退出代码,而不使用带有中断条件的while true循环重写此示例,如上所示?
除了众所周知的while循环外,POSIX还提供了一个until循环,无需取消my_command的退出状态.
# To demonstrate my_command () { read number; return $number; } until my_command; do if [ $? -eq 5 ]; then echo "Error was 5" else echo "Error was not 5" fi # potentially,other code follows... done