如何获得退出状态在bash循环 [英] How to get the exit status a loop in bash

查看:105
本文介绍了如何获得退出状态在bash循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何检查使用$ pviously执行命令$ P $的状态?我们可以使用exit命令作出这样的状态。但在bash的循环总是返回状态0,是有什么办法可以破解一些状态的循环。

 #!/斌/庆典
而真正的

        如果[-f/测试];然后
                突破###在这里,我想用一些状态退出
        科幻DONE
回声$? ##在这里我要检查状态。


解决方案

循环的状态是执行的最后一个命令的状态。你可以使用break跳出循环,但如果突破成功,则循环的状态将是 0 。但是,你可以使用一个子shell退出,而不是破坏。换句话说:

 为我在酒吧foo的;做回声$ I;假;打破;完成的;回声$? #环路成功
(因为我在美孚吧;不要回声$ I; FALSE;退出;完成);回声$? #循环失败

您也可以把循环的功能和它返回一个值。

I know how to check the status of the previously executed command using $?, and we can make that status using exit command. But for the loops in bash are always returning a status 0 and is there any way I can break the loop with some status.

#!/bin/bash
while true
do
        if [ -f "/test" ] ; then
                break ### Here I would like to exit with some status
        fi

done
echo $?  ## Here I want to check the status.

解决方案

The status of the loop is the status of the last command that executes. You can use break to break out of the loop, but if the break is successful, then the status of the loop will be 0. However, you can use a subshell and exit instead of breaking. In other words:

for i in foo bar; do echo $i; false; break; done; echo $?  # The loop succeeds
( for i in foo bar; do echo $i; false; exit; done ); echo $? # The loop fails

You could also put the loop in a function and return a value from it.

这篇关于如何获得退出状态在bash循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆