How do I set $? in functions called by PS1?

Viewed 401

I currently have a prompt in bash that calls a function to output the return code of the last command run (if non-zero):

exit_code_prompt()
{
    local exit_code=$?
    if [ $exit_code -ne 0 ]
    then
        tput setaf 1
        printf "%s" $exit_code
        tput sgr0
    fi
}


PS1='$(exit_code_prompt)\$ '

This works rather nicely, except for $? not resetting unless another command is run:

$ echo "works"
works
$ command_not_found
bash: command_not_found: command not found
127$ 
127$ 
127$ 
127$ echo "works"
works
$

Is it possible to reset/unset the value of $? for the parent shell the first time exit_code_prompt() is run such that it does not continue to repeat the value in the prompt?

Many thanks, Steve.

1 Answers
Related