Change iTerm background color on ssh

Recorded on May 7th, 2014

I use ssh all the time but I often switch to iTerm and forget that I am in an ssh window instead of a local one. I have looked for solutions for this before but never found any I like.

Today I found two.

  1. will change the color of the tab bar or window bar (if there’s only one tab). That’s a nice effect, but I wanted to color the entire window, because I didn’t want it to be something subtle that I might miss.
  2. will change the entire background of the iTerm window.

That second option was what I wanted.

The key is a function called set_term_bgcolor:

function set_term_bgcolor {
  local R=$1
  local G=$2
  local B=$3
  /usr/bin/osascript <<EOF
tell application "iTerm"
  tell the current terminal
    tell the current session
      set background color to {$(($R*65535/255)), $(($G*65535/255)), $(($B*65535/255))}
    end tell
  end tell
end tell

Once you have that in your ~/.zshrc you can change the color at any time by typing

set_term_bgcolor R G B

where R, G, and B are numbers from 0-255. For example, if I wanted to make the background completely white, I would use

set_term_bgcolor 255 255 255

If you aren’t familiar with RGB colors, you can find out more about them via Google

Once I had that function in place, I just needed to create another function for ssh which will change the color when I ssh and change it back when I finish.

function ssh {

    set_term_bgcolor 255 255 204

    command ssh $@

    set_term_bgcolor 255 255 255

command ssh $@ tells the function to pass along any arguments to the real ssh command from our $PATH.

So now when I ssh somewhere, the entire window gets a new background color, and when I’m done it goes back to white (my default color). If you wanted to make specific colors for specific ssh connections, you could do that just by creating a specific function. For example, if I wanted a green background anytime I ssh to Dreamhost, I could use this:

function dh {

    set_term_bgcolor 0 255 0

    command ssh -v

    set_term_bgcolor 255 255 255

and then whenever I want to ssh to Dreamhost I’d just need to type dh.

For me, just having any ssh window colored is enough, I don’t need different colors for different hosts.