Last Updated: February 25, 2016
·
890
· stevebenner

Enhance your terminal prompt to show current Ruby version

I've you've ever found yourself at a terminal thinking What version of Ruby is currently active? then perhaps this tip is for you. Operating multiple Ruby installations has never been easier thanks to tools like the elegant [chruby][1], which lets you view the status of your Rubies in a single command. But no matter which Ruby manager you use, awareness of your evironment configuration is essential to proper Ruby development! I found myself checking my version so often that it merited some form of automation.

With a little bit of Bash, I came up with a fun solution that anyone can implement (it's just a single line of code!) to permanently populate your shell prompt with this information, turning something like this:

cmptr:dir usr$

into this:

[ruby 2.1.3p242] cmptr:dir usr$

The key to 'hacking' your prompt is setting the variable PS1, ideally in some shell profile that is automatically loaded. To produce a prompt like the one above, use a value of:

PS1="$(tput setaf 1)[$(ruby -v | grep -o 'ruby ([^\( ]*)')]$(tput sgr0) \h:\W \u\$ "

It looks messy but the explanation is simple. The first part is an interpolated command which changes the text color to RED, a totally aesthetic touch you don't really need. I chose red for Ruby, but it doesn't matter.

$(tput setaf 1)

The most reliable way of determining your Ruby version is to run the executable itself, which will output version and build info when passed the -v flag. I pipe this into grep to trim it down to essentials, using the -o flag which makes it return only what matches the given regex. The enclosing brackets are just aesthetic as well here.

[$(ruby -v | grep -o 'ruby ([^\( ]*)')]

Last but not least we reset the coloring, which prevents the rest of the prompt from coming out red.

$(tput sgr0)

[1]: https://github.com/postmodern/chruby

1 Response
Add your response

good

over 1 year ago ·