My Bash $PS1
September 07, 2018
I spend a lot of time on the command-line, and every so often I run across a new
way to make it show me more useful information. Today’s update: displaying the
real time the last command took to run inline in the prompt. I can’t take credit
for the idea - I found the approach on this excellent blog post - but
I’ve got a few other interesting pieces in my $PS1
so I figure it’s
worth sharing briefly. Here’s what my shell environment looks like:
All of these functions use shell variables to pass info along to the $PS1
.
I’ve found that this approach along with $PROMPT_COMMAND
leads to the fewest
levels of shell quoting & interpolation hell. The only thing to remember is that
in your $PS1
you need to escape the $
so that it’s interpolated when the
prompt prints rather than when the $PS1
is set. Wrong: PS1=${my_dynamic_var}
,
Right: PS1=\${my_dynamic_var}
.
current git branch
This one is pretty standard, ask git
for your current branch. If it’s non-empty
wrap and color it for easy visual grepping.
last command’s exit status
I’ve had this in my $PS1
for years now - who doesn’t love a smiley face to let
you know that your last command didn’t explode?
last command’s time elapsed
This is a little bit more involved - the basic idea here is that we start a timer
before running every command with trap
and stop it when the prompt refreshes,
as the last thing to run in $PROMPT_COMMAND
. I’ve updated Jake’s example code
to format the timing a little bit more densely - 1m31s
instead of 91s
and
1hr31m0s
instead of 91m0s
.
plumbing
And finally it’s time to hook the functions up to $PROMPT_COMMAND
so that they
refresh as you navigate around in your terminal
and to set your $PS1
variable so that the whole show works. One last note:
I’m a huge fan of a two-line terminal prompt so that it’s easy to see which
directory you’re in and still have plenty of space to type out long commands
without hitting line wrapping. Here’s the $PS1
I use on pretty much every
machine I log into:
Finally, for easy copy-pasta, here’s a gist with
all of this code in one place. Stick it in your ~/.bash_profile
and never worry
about running time
by hand again!
Comments