Is there an elegant way to store and evaluate return values in bash scripts?

后端 未结 6 2104
傲寒
傲寒 2020-12-01 20:03

I have a rather complex series of commands in bash that ends up returning a meaningful exit code. Various places later in the script need to branch conditionally on whether

6条回答
  •  失恋的感觉
    2020-12-01 20:13

    If you don't care about the exact error code, you could do:

    if long_running_command | grep -q trigger_word; then
        success=1
        : success
    else
        success=0
        : failure
    fi
    
    if ((success)); then
        : success
    else
        : failure
    fi
    

    Using 0 for false and 1 for true is my preferred way of storing booleans in scripts. if ((flag)) mimics C nicely.

    If you do care about the exit code, then you could do:

    if long_running_command | grep -q trigger_word; then
        status=0
        : success
    else
        status=$?
        : failure
    fi
    
    if ((status == 0)); then
        : success
    else
        : failure
    fi
    

    I prefer an explicit test against 0 rather than using !, which doesn't read right.

    (And yes, $? does yield the correct value here.)

提交回复
热议问题