Bash shell prompt: where is $RET?

I was reading this and ended up with the following:

# Stores the status of each command in $RET
PROMPT_COMMAND='RET=$?;'
# A colour.
RED_SHELL='\e[0;36m'
# Prints "Status 1" if RET is 1, for example.
RET_VISUALISE='$(if [[ $RET != 0 ]]; then echo -ne "Status \[$RED_SHELL\]$RET\n" && RET=0; fi;)'
# What to print for each prompt.
PS1="$RET_VISUALISE\[\e]0;\w\a\]\n\[\e[32m\]\u@\h \t \[\e[33m\]\w\[\e[0m\]\n\$ "

This does almost what I want, except when I press Enter,Enter,Enter multiple times after a command that returned status != 0. In this case it prints "Status 1" every time I press Enter.

This is what the && RET=0; part was supposed to get rid of.

Also, I don't understand why env | grep RET only shows the PS1 contents. What is the scope of $RET ?

0

1 Answer

You're overriding your RET=0 with RET=$? when the next prompt is printed without having executed a command in between. $? returns the last executed command's return value, and that's still 1.

Bash allows you to trap errors in executed commands and execute code in response to that (once):

function err_handle { RET=$? if [[ $RET != 0 ]]; then echo -ne "Status $RED_SHELL$RET\n" fi
}
trap 'err_handle' ERR
4

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like