Colorize Terminal When Using SSH

Mon, Feb 17, 2014 2-minute read

In this tutorial I’m going to show you how to set up your .bashrc to colorize the terminal automatically whenever you are using SSH.

The reason for this should be obvious, it can get difficult to distinguish multiple terminals and issuing commands on the wrong shell can get you into big trouble.

Realizing I ran the command on the wrong server

by DEVOP REACTIONS @tumblr

All you have to do is write an alias in which you define the colors you want for the font and the background:

alias ssh=”tput setf 2; tput setb 0; ssh”

This replaces ssh and puts the commands tput setf (foreground/font color) and tput setb (background color) before the actual ssh command. In case setf and setb don’t work for you, try setaf and setab.

You can also create individual aliases for different ssh connections:

alias example=”tput setf 0; tput setb 4; ssh user@example.com

alias domain=”tput setf 1; tput setb 0; ssh root@domain.com

In these cases you only have to execute the respective alias like example or domain instead of writing ssh. However, you can not use an ssh alias together with individual ones because it would overwrite the other tput settings.Probably the best solution for both a general ssh colorization and an individual one is to use a different alias for general ssh commands. Here’s an example:

alias sshc=”tput setf 2; tput setb 0; ssh”

alias example=”tput setf 0; tput setb 4; ssh user@example.com

alias domain=”tput setf 1; tput setb 0; ssh root@domain.com

Don’t forget to reload your .bashrc file:

source .bashrc

Here is a screenshot in which you can see the colors set with tput setf 2 and tput setb 0:

 

As you can see in the first picture, only the background of the characters is changed at first but after you issue a “clear” the whole background of the terminal has the new color. I don’t know why this happens or if it’s a bug, if you find out please let me know through the comments.

Color Code for tput:

0 – Black

1 – Red

2 – Green

3 – Yellow

4 – Blue

5 – Magenta

6 – Cyan

7 – White

You can find more info about tput here:

http://linux.101hacks.com/ps1-examples/prompt-color-using-tput/