How to get the exit status a loop in bash

后端 未结 8 821
醉梦人生
醉梦人生 2020-12-16 15:38

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

8条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-16 16:01

    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.

提交回复
热议问题