Search code examples
bashshellexit-code

Preserve exit code when using '$PROMPT_COMMAND'


I have the following code (simplified for clarity) which is called by $PROMPT_COMMAND after every command:

function previous_command_status() 
{
    exit_code=$?;
    if [ $exit_code -eq 0 ]; then
        echo "Command successful"
    else
        echo "Command failed with exit code $exit_code"
    fi
}

The problem is, it seems the [ $exit_code -eq 0 ] part is changing the exit code, so I am unable to use or store the exit code after the command has finished running. For example:

$ ./failing_script.sh
Command failed with exit code 255
$ echo $?;
1   # this is the exit code of the 'if' statement, not of 'bad'

I cannot "pass the value along", because if I add the line exit $exit_code inside the function, the terminal window closes immediately.

Is there any way for me to "preserve" the exit code of the previous command, or run a set of commands in such a way that they won't modify the exit value?


Solution

  • You can't preserve it. Even if you use case statements echo would still alter it. However you can put it back with return:

    exit_code=$?;
    if [ $exit_code -eq 0 ]; then
        echo "Command successful"
    else
        echo "Command failed with exit code $exit_code"
    fi
    return "$exit_code"
    

    You can use another global variable to store the code however.