1. Technology
You can opt-out at any time. Please refer to our privacy policy for contact information.

How to Display Your Ruby Version in Your Bash Prompt


With RVM installed on your system, it's easy to have many versions of Ruby installed. And, especially if you switch between them often, it's easy to forget which Bash command prompt is using which Ruby version. You can solve this by putting your Ruby version in your Bash prompt.

Compared to Ruby, Bash is a convoluted black art. Even if you know how to do basic things with Bash scripting, it can always come back to bite you in some unexpected way. For that reason, this article will guide you through what would otherwise be a simple task.

The prompt Bash displays in the terminal window is controlled by the PS1 Bash variable. A typical Bash prompt is as follows.

PS1="\W\$ "

Each of these backslash constructs will get replaced with something meaningful. For example, the \W will get replaced with the current directory, and \$ with the prompt character ($ for most users, # for root users). But what we need to do is run a command every time the prompt is displayed.

To run a command as part of a string, you have to use the subshell construct. Bash, just like Ruby, will expand a number of constructs inside of double-quoted strings. If you were to run the following Bash command, when the string is interpreted, it will run the command inside of the $(...) construct and put its output into the string.

$ echo "$(ruby -e 'print RUBY_VERSION')"

So how do we put this together? I'm going to show you first, and explain after, because it's not obvious at first. To use this prompt, open your ~/.bashrc file in a text editor and add the following line to the end.

PS1='$(ruby -e "print RUBY_VERSION") \W\$ '

If Bash only expands the subshell construct in double-quoted strings, why use a single quoted string? If you use a double-quoted string when setting the PS1 variable, it will run the subshell once, and not every time the prompt is displayed. Instead, if you use single quotes (or "hard" quotes), the subshell construct will remain intact until PS1 is used to display the prompt, and then it will be interpolated.

After setting this as your prompt, it will look something like this. That last "koans" part is the current directory.

1.8.7 koans$
  1. About.com
  2. Technology
  3. Ruby
  4. Advanced Ruby
  5. How to Display Your Ruby Version in Your Bash Prompt

©2014 About.com. All rights reserved.