How to install $? in functions called PS1?

Currently, I have a prompt in bash that calls a function to output the return code of the last command run (if not equal to 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)\$ ' 

Does this work pretty well except for $? not reset unless another command is executed:

 $ 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 / disable the value of $? for the parent shell the first time exit_code_prompt() run so that it does not continue to repeat the value in the prompt?

Thanks a lot, Steve.

+6
source share
1 answer

The problem is that if you do not issue another command, $? does not change. Therefore, when your invitation is reevaluated, it correctly emits 127 . There really is no workaround for this other than manually entering another command at the prompt.

edit: Actually, I lied, there are always ways to save state, so can you save the value of $? and check if it has changed, and clear the invitation, if any. But since you are in a subshell, your options are quite limited: you will need to use a file or something as dirty to save the value.

+3
source

Source: https://habr.com/ru/post/922382/


All Articles