Show the exit status in your $PS1

As an update to my earlier article, a friend gave me an idea of how to make my $PS1 even better… First, the relevant part of my ~/.bashrc:

ps1_prompt() {
	local ps1_exit=$?

	if [ $ps1_exit -eq 0 ]; then
		#ps1_status=`echo -e "\[\033[32m\]"'\$'"\[\033[0m\]"`
		ps1_status=`echo -e "\[\033[1;31m\]"'\$'"\[\033[0m\]"`


	if [ "$(__git_ps1 %s)" != '' -a "$(__git_ps1 %s)" != 'master' ]; then
		ps1_git=" (\[\033[32m\]"$(__git_ps1 "%s")"\[\033[0m\])"

	PS1="${debian_chroot:+($debian_chroot)}\u@\h:\[\033[01;34m\]\w\[\033[00m\]${ps1_git}${ps1_status} "

# preserve earlier PROMPT_COMMAND entries...

If you haven’t figured it out, the magic is that the trailing $ prompt gets coloured in red when the previous command exited with a non-zero value. Example:

james@computer:~$ cdmkdir /tmp/ttboj # yes, i built cdmkdir
james@computer:/tmp/ttboj$ false
james@computer:/tmp/ttboj$ echo ttboj
james@computer:/tmp/ttboj$ ^C
james@computer:/tmp/ttboj$ true
james@computer:/tmp/ttboj$ cd ~/code/puppet/puppet-gluster/
james@computer:~/code/puppet/puppet-gluster$ # hack, hack, hack...

You can still:

$ echo $?

if you want more specifics about what the exact return code was, and of course you can edit the above ~/.bashrc snippet to match your needs.

Hopefully this will help you be more productive, I know it’s helping me!

Happy hacking,


5 thoughts on “Show the exit status in your $PS1

  1. I don’t know enough to know why, but I had to change the ps1_status lines to:



    ps1_status=echo -e “33[1;31m$33[0m”

    If I didn’t the escape sequences (in particular the backslash and brackets) were included in the prompt.

    This is such a great idea, thanks for sharing!

    • Hm, peculiar! Well, it worked as is for me, but glad you got it working anyways!

      I’m happy you’re enjoying the idea– I love it too!

      You can obviously be more creative and change the output. Colour blind individuals, might prefer to instead show an ‘:(‘ (unhappy face) where the command is non-zero, and other users might like echoing the value.

  2. That was great!

    I also ran into this vaguely related issue, since I wasn’t previously including my git status, after I curled the file I added the following to my .bash_profile:

    if [ -f ~/ ]; then
    source ~/

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s