6

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.

kojiro
  • 74,557
  • 19
  • 143
  • 201
Stephen Wattam
  • 525
  • 2
  • 12
  • Why do you want to do this? This may give you additional trouble, if you want to test some script snippet manually over the command line. – anishsane Nov 19 '12 at 05:47

1 Answers1

3

The issue is that if you don't issue another command, $? isn't changing. So when your prompt gets reevaluated, it is correctly emitting 127. There isn't really a workaround for this except manually typing another command at the prompt.

edit: Actually I lied, there are always ways to store state, so you can store the value of $? and check if it's changed, and clear the prompt if it has. But since you're in a subshell, your options are pretty limited: You'd have to use a file or something equally dirty to store the value.

kojiro
  • 74,557
  • 19
  • 143
  • 201
  • 1
    I don't need to store state, merely reset it after the printf if it's not equal to 0 --- I know when I wish to do it, just not how (and/or if it's possible) – Stephen Wattam Aug 08 '12 at 17:08
  • @StephenWattam but if you don't store state, how can you tell the difference between a prompt immediately following a command and a prompt *not* following a command? – kojiro Aug 08 '12 at 17:11
  • I was coming at this from a different angle, using `$?` as the state and setting it to zero after one output. – Stephen Wattam Aug 08 '12 at 17:15
  • @StephenWattam right, but I don't think there's a way to do that within the `PS1` or `PROMPT_COMMAND`. Thus, you need an external way to check if it has changed. You can't simply force it back to `0`. – kojiro Aug 08 '12 at 17:17
  • I feared as much. The only solution I could come up with was `PROMPT_COMMAND="bash"`, but that's hilariously poor :-). – Stephen Wattam Aug 08 '12 at 17:24
  • 2
    Without being able to alter how bash runs its prompts, it seems the scoping rules do indeed prevent me from touching anything --- Many thanks for the help. This has to be the only time ever someone has wanted features from PHP in another language :-). – Stephen Wattam Aug 08 '12 at 17:32