Changing Your Terminals Appearance Based on Environment Variables

I’m scared of the production database. Anyone else? I can copy the production database down to my local instance anytime I want, so I have an up-to-date version I can work off of while developing locally, but sometimes I actually need to make changes in production. This is fine, but I get nervous that I’ll do that, and then continue working off of production, when I don’t mean to. (No matter how careful I am, I am human, and humans make mistakes). So I decided to protect myself from … myself.

When I open a new terminal window and am in the Django virtualenv that I use for the codebase, the DATABASE_URL environment variable is automatically set to my local instance via the postactivate file, and my terminal looks like this:

A quick command changes both the DATABASE_URL environment variable to point to the production instance, and also makes my terminal look like this:

Won’t accidentally forget which database you’re connected to with your terminal looking like that, will you? I also have one to connect to staging, giving me this:

It’s pretty simple. iTerm has profiles, which allows you to change anything about the appearance of your terminal. I have 3, my default, production, and staging profiles — they’re all basically the same except for the background color. Once you’ve created your profie(s), the following script goes in a file by whatever name you like (no file extension necessary) in /usr/local/bin:

#!/bin/bash
export DATABASE_URL=<Your database URL goes here. You don't get to see mine>
echo -e "\033]50;SetProfile=Production\a"

In the line beginning with echo, you can change the word “Production” to whatever you named the relevant iTerm profile.

You can then make the file executable by running:

chmod +x <filename>

and then actually run it with:

source <filename>

Voilà!

(Beware: if you forget the source before the filename, your terminal’s appearance will change, but the environment variable won’t.)