Which environment is it, really?

February 24, 2010 by alex

UPDATE : April 21, 2010


I like how this guy does something similar, but uses variable names for the color codes to make the resulting $PS1 string a bit more readable.

Rails uses the environment variable $RAILS_ENV to control which set of configuration files should be loaded. This includes, among many other things, what database to connect to. I tend to have lots of terminal windows open, doing several things at once. There are lots of circumstances where it’s useful to switch to a different Rails environment for some tasks. The danger here, though, is that plenty of things you might do in a personal local development environment aren’t at all safe to do in a production environment. (Dropping and re-loading test data into the production database is a particular no-no.)

I used to frequently echo $RAILS_ENV to check what a particular terminal window was set to. The trouble is it’s easy to forget to do this. Having multiple terminals in multiple environments becomes a time bomb waiting to go off.

The solution I cooked up is to add some information about my $RAILS_ENV right in the terminal prompt. The concept is pretty simple, but getting the particular bash incantation correct took some doing. Adding this to your .profile in OSX will give you a colored prompt. Green for ‘development’, and red for any other environment. Should be pretty easy to fine-tune for your specific needs.

export RAILS_ENV=development
export PS1='`if [ "$RAILS_ENV" == "development" ]; then echo -n "\[\033[01;32m\]"; else echo -n "\[\033[01;31m\]"; fi;`$RAILS_ENV:\[\033[01;34m\]\w\[\033[00m\]\$ '

Here’s what it looks like in action: I do most of my work in OSX 10.5, which uses GNU bash, version 3.2.17(1)-release (i386-apple-darwin9.0) . I suspect this could be tweaked to work in more versions of bash.

☙ ☙ ☙