Visual feedback of the exit status of the previous command in bash

Put this in your .bashrc, and the current directory in your PS1 will be printed green if the previous command had exit state 0, red otherwise. No more typing 'echo $?', ' && echo ok', '|| echo failed' etc on the command line.

if [ $(tput colors) -gt 0 ] ; then
    RED=$(tput setaf 1)
    GREEN=$(tput setaf 2)
    RST=$(tput op)
fi

bash_prompt_command() {
        last_exit=$?
        exit_to_color=$RED
        [ $last_exit == 0 ] && exit_to_color=$GREEN
}

export PROMPT_COMMAND=bash_prompt_command

PS1="\u@\h \[\$exit_to_color\]\W\[$RST\] \$"

( Inspired by this post )

Add comment