Creating a Bash command prompt with a red $ after failure of previous command Creating a Bash command prompt with a red $ after failure of previous command shell shell

Creating a Bash command prompt with a red $ after failure of previous command


Use the PROMPT_COMMAND variable, which is executed before each primary prompt according to the bash man page.

For example (this doesn't work yet, I'm trying to get it working right, but I think it's possible):

PROMPT_COMMAND="if [ \$? = 0 ]; then DOLLAR="${WHITE}\$${NORMAL}"; else DOLLAR="${RED}\$${NORMAL}"; fi"

Edit: due to frustrations with executing commands and nonprinting characters inside PS1 (the \[ and \] sometimes get printed out literally instead of used as hints to PS1), I've come up with this (replace ... with whatever you want in your prompt):

PROMPT_COMMAND='if [ $? = 0 ]; then DOLLAR_COLOR="\033[0m"; else DOLLAR_COLOR="\033[31m"; fi'PS1='...\[$(echo -ne $DOLLAR_COLOR)\]$\[\033[m\] '

Of course, using $() you could put whichever parts of this you like inside PS1 instead of using PROMPT_COMMAND, I just like it this way so that PROMPT_COMMAND contains the logic and PS1 contains the display commands.


I got it to work:

PROMPT_COMMAND='if [ $? = 0 ]; then PS1="\[\e[32;1m\]\u@\[\e[0m\e[30;47m\]\H\[\e[0m\]:\[\e[34;1m\]\w\[\e[0m\]$ "; else PS1="\[\e[31;1m\]\u@\[\e[0m\e[31;47m\]\H\[\e[0m\]:\[\e[31;1m\]\w\[\e[0m\]$ "; fi'

enter image description here

Standing on the sholders of @jtbandes. @jtbandes is the original author of the idea.


Here is Alexsandr's answer modified to display the red color only when a command fails and not when you push enter on an empty command line, as Stéphane requested.

trap 'PREVIOUS_COMMAND=$THIS_COMMAND; THIS_COMMAND=$BASH_COMMAND' DEBUGread -r -d '' PROMPT_COMMAND << 'END'    if [ $? = 0 -o $? == 130 -o "$PREVIOUS_COMMAND" = ": noop" ]; then        PS1='\[\e[32;1m\]\u@\[\e[0m\e[30;47m\]\H\[\e[0m\]:\[\e[34;1m\]\w\[\e[0m\]$ '    else        PS1='\[\e[31;1m\]\u@\[\e[0m\e[31;47m\]\H\[\e[0m\]:\[\e[31;1m\]\w\[\e[0m\]$ '    fi    : noopEND