문제

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.

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top