A Better bash Prompt

1. April 2018

Recent work has included a significant amount of time spent ssh‘d into different hosts; to avoid confusion about which machine I was executing commands on I decided to update my default bash prompt to include some additional information. If everything’s going well, my prompt looks like this:

[1722][Nick@prozess: ~]$

Though simple at first glance, it’s quite information dense. The first bit, [1722] tells me this the 1722nd command in my bash_history, meaning I can easily rerun it with !1722.

The colour coding of the next square bracket delimited section means that the last command I ran executed successfully ($0 == 0), and I also know my username, my hostname, and my relative path. If I ssh into my bounce box or my Windows build machine, it’s now immediately clear which environment I’m operating in. Interested in trying it yourself?

My full prompt command is 218 characters of bash-specific jankery; if you can imagine the following is bash-like psuedo-code that returns a string, the logic is like this:

1
2
3
4
5
6
7
8
9
10
11
12
[\!]
if [[ $? = "0" ]]; then
    echo "make following text green"
else
    echo "make following text red"
fi
[\u@\h:
if (( `pwd|wc -c|tr -d " "` > 18 )); then
    echo "\"\\W\""
else
    echo "\"\\w\""
fi

All of the escaped sigils, like \w and \! are described in detail by the bash man page; refer to your system for full details. Featured here are:

  • \!: The history number of this command
  • \u: The username of the current user
  • \h: The hostname up to the first .
  • \W, \w: The full path basename of the current directory, respectively.

The full PROMPT_COMMAND, suitable for copying and pasting into your own .bashrc can be found here.