How to get the exit status a loop in bash

后端 未结 8 817
醉梦人生
醉梦人生 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 15:58

    Git 2.27 (Q2 2020), offers a good illustration of the exit status in a loop, here within the context of aborting a failing test early (e.g. by exiting a loop), which is to say "return 1".

    See commit 7cc112d (27 Mar 2020) by Junio C Hamano (gitster).
    (Merged by Junio C Hamano -- gitster -- in commit b07c721, 28 Apr 2020)

    t/README: suggest how to leave test early with failure

    Helped-by: Jeff King

    Over time, we added the support to our test framework to make it easy to leave a test early with failure, but it was not clearly documented in t/README to help developers writing new tests.

    The documentation now includes:

    Be careful when you loop

    You may need to verify multiple things in a loop, but the following does not work correctly:

    test_expect_success 'test three things' '
        for i in one two three
        do
          test_something "$i"
        done &&
        test_something_else
    '
    

    Because the status of the loop itself is the exit status of the test_something in the last round, the loop does not fail when "test_something" for "one" or "two" fails.
    This is not what you want.

    Instead, you can break out of the loop immediately when you see a failure.
    Because all test_expect_* snippets are executed inside a function, "return 1" can be used to fail the test immediately upon a failure:

    test_expect_success 'test three things' '
        for i in one two three
        do
          test_something "$i" || return 1
        done &&
        test_something_else
    '
    

    Note that we still &&-chain the loop to propagate failures from earlier commands.

提交回复
热议问题