shellif-statementcommand-lineerror-handling

How to get the exit code when running `if ! command; then`?


When I want to take action on a failure I do:

if ! commmand; 
then
    echo $?
fi

But the exit code is always 0.


Solution

  • If you need to exit status later, you might consider saving it in a variable:

    command
    status=$?
    if (( status != 0 )); then
        echo $status
    fi