Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 570
Stephen Wattam Avatar asked Aug 08 '12 16:08

Stephen Wattam


People also ask

How do I permanently set a PS1 variable in Linux?

In Linux, the PS1 system variable is used to change the prompt setting. To change the Linux prompt permanently, you need to modify the . bashrc file which initializes the interactive shell session whenever the system starts.

Where is PS1 set?

PS1 is a primary prompt variable which holds \u@\h \W\\$ special bash characters. This is the default structure of the bash prompt and is displayed every time a user logs in using a terminal.

How do I change the $PS1 prompt in Linux bash?

You can change the BASH prompt temporarily by using the export command. This command changes the prompt until the user logs out. You can reset the prompt by logging out, then logging back in.

What is PS1 in Linux?

PS1 is a primary prompt variable. Currently it holds \\u@\\h:\\w\\$ special bash characters. This is the default structure of the bash prompt on many Linux systems and is displayed every time you log in using a terminal.


1 Answers

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.

like image 165
kojiro Avatar answered Oct 10 '22 01:10

kojiro