Drew's Blog - Home - Archive

Making your $ more informative

This is about your terminal prompt, not about money. Sorry to disappoint.

But seriously, I was watching a RailsCast earlier today and I noticed that the presenter was displaying his current git branch in his terminal prompt. I wondered "How can I do this?" So I asked Google. The first thing I tried was not exactly what I was looking for. I don't like having a bunch of pastel colors all over my terminal, and that the hostname, path, and username weren't quite in the order that I wanted. So I went back to my search results, and I found this. Here are the relevant bits:

export PS1=" "

Between the quotation marks, you can add the following lines to customize your Terminal prompt:

  • \d – Current date
  • \t – Current time
  • \h – Host name
  • \# – Command number
  • \u – User name
  • \W – Current working directory (ie: Desktop/)
  • \w – Current working directory, full path (ie: /Users/Admin/Desktop)

So then I combined the function from the first search result and came up with this:

parse_git_branch() {   git branch --no-color 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/\[\1]/' } export PS1='\h:\w$(parse_git_branch) \u$ '

Which looks like this:

inglis-mac:~/intersect[work] drew$ [blinking cursor]

Now, recently I've been using RVM (both with Intersect and with other projects), and I decided that I wanted it to show up in the results, but only if I was using an environment other than system. This can pretty easily (if you remember that + cannot be used in sed regex) be accomplished by this function:

show_rvm_state() {   rvm current | sed -e 's/system//' -e 's/\(..*\)/[\1]/' #'..*' = '.+' on OSX }

The first bit kills it if it's system and the second bit puts it in brackets (so it looks pretty).

I also added a time function that only shows the hour and minute, so now my final everything looks like this:

parse_git_branch() {   git branch --no-color 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/[\1]/' } show_rvm_state() {   rvm current | sed -e 's/system//' -e 's/\(..*\)/[\1]/' #'..*' = '.+' on OSX } short_time() {   date "+%H:%M" } export PS1='$(short_time) \h:\w$(parse_git_branch)$(show_rvm_state) \u$ '

If there's an easier way to do the "short_time" bit, let me know. I didn't want to spend too much time on this. I'm also thinking about taking out the system name and/or the username. What do you guys think?

If you've read this far, you should probably follow me on Twitter.

See more posts

Drew writes code for fun and (sometimes) profit. He's currently studying Computer Science at Carnegie Mellon University. He has previously worked at Facebook, Amazon, and a startup called Intersect.