user14241752
user14241752

Reputation:

Change last character's color of PS1v promt based on exit status of previous command

I've customized my .bashrc settings similar to default's PS1 settings from Clear Linux. My file contents these lines:

EXIT="$?"
BLUE="\[\e[38;5;39m\]"
RED="\[\e[31m\]"
ORANGE="\[\e[38;5;208m\]"
WHITE="\[\e[0m\]"
    if [ "$EXIT" = "0" ]; then
          endchar="${BLUE}\\$""$WHITE"
    else
          endchar="${RED}\\$""$WHITE"
    fi
    
    if [ "$UID" = "0" ]; then
          username="${RED}\u${WHITE}"
    else
          username="${BLUE}\u${WHITE}"
    fi  

host="${ORANGE}\H${WHITE}"
dir="${BLUE}\w${WHITE}"
PS1="${username}@${host} ${dir} ${endchar} "

The file is sourced with no errors on login or opening new terminal windows, with one exception: Last character in resulting PS1 string remains forever blue, though i type mistakes on terminal.

Expected behaviour of my settings is that prompt's last character $ turns red when exit status of previous command is greater than 0.

Any suggestions? Thanks in advance

Upvotes: 1

Views: 344

Answers (2)

pynexj
pynexj

Reputation: 20688

Just give you another example:

function _ps1_command()
{
    local rcode=$?

    if (( rcode )); then
        g_prompt_color=$'\e[1;31m'
    else
        g_prompt_color=$'\e[0m'
    fi
}
PROMPT_COMMAND=_ps1_command
PS1='[\w] \[$g_prompt_color\]\$\[\e[0m\] '

enter image description here

Upvotes: 1

Ivan
Ivan

Reputation: 7277

Add this color code to the end

DEF='\e[0m' #Default color and effects
PS1="${username}@${host} ${dir} ${endchar}$DEF "

And take a look here

Upvotes: 1

Related Questions