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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With