Dan Stutzman

Different color shell prompts for different servers

Published 2014-01-05

It's all too easy to accidentally run the right command -- on the wrong server. (Hopefully you're using some automated deployment process to roll out new code to production servers, instead of directly running shell commands on production servers. And hopefully you're writing and testing code on your own machine, not some shared development server. Even so, it's likely you have SSH access to at least one machine).

To reduce the chance of mistakes or confusion, you can use ANSI escape codes to change the background color of your shell prompt, otherwise known as the PS1 environment variable. Just add one of the following lines to the hidden file .bashrc in your home directory:

  • Reverse video (black on white text) for my MacBook Pro:
    export PS1="\[$(tput smso)\]\w\$\[$(tput rmso)\] "
  • Gray text on red background, showing username and hostname:
    export PS1="\[$(tput setab 1)$(tput setaf 7)\]\u@\h:\w\$\[$(tput sgr0)\] "
  • Black text on green background, showing username and hostname:
    export PS1="\[$(tput setab 2)$(tput setaf 0)\]\u@\h:\w\$\[$(tput sgr0)\] "
  • Search for "bash prompt generator" for an interactive program to customize your own.

Note that when you edit your .bashrc, changes won't take effect until you open a new shell window.