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:
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@\`friendly_hostname`:
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 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.
- see below for myfriendly_hostname
function\W
,\w
: The full path basename of the current directory, respectively.
The full PROMPT_COMMAND
, suitable for copying and pasting into your own
.bashrc
:
1
2
3
4
5
6
friendly_hostname() {
: 'Can not change the hostname of my work MBP, so use sed to replace the string in my prompt'
hostname | sed 's/APKPHTD6A4834F/nike/'
}
PROMPT_COMMAND='PS1="\[\033[0;33m\][\!]\`if [[ \$? = "0" ]]; then echo "\\[\\033[32m\\]"; else echo "\\[\\033[31m\\]"; fi\`[\u@`friendly_hostname`: \`if [[ `pwd | wc -c |tr -d " "` -gt 18 ]]; then echo \"\\W\"; else echo \"\\w\"; fi\`]\$\[\033[0m\] ";'