Dynamically change title of Mac OS X Terminal in SSH sessions

I have been using Termina.app since I started using Mac OS X several years ago. In general I feel pretty comfortable by using it and I didn’t need to look for alternatives. Obviously, the command I run most often on the command line is the ssh(1) client, which I think is among the most used tool by Unix server administrators.

This terminal emulator offers a wide range of customizations, including the possibility to assign a custom title to each tab or window you open, but I’d like to make the name of the host I connect to appear as custom title automatically, as soon as I connect to it, then changing back after I disconnect to whatever it was before.

I thought it was a pretty trivial task to accomplish, but it has shown to be not so easy as I supposed. The best method I found is to create a simple shell script to manage this tricky operation. Thus I’m now posting the solutions for anyone who might found it useful or could suggest a simpler approach… here it is:

#!/bin/sh
#
# This script changes the current Terminal window title and starts
# an ssh session with the host indicated in the argument
#
if [ $1 ] ; then
 oldtitle=`arch -i386 osascript -e 'tell application "Terminal" \
           to get custom title of front window'`
 newtitle=`echo $1 | sed -e 's/.*\@\(.*\)/\1/'`
 echo "\033]0;$newtitle\007"
 ssh $1
 echo "\033]0;$oldtitle\007"
else
 echo "ERROR: you must enter a valid host name as argument."
 echo "\033]0;Terminal\007"
fi

If you save this lines in a file called ~/bin/remote and chmod it to 755, you can use the following string to connect to your SSH server:

% remote user@server.domain

The custom title of the current window will be set by getting the hostname part of the command argument before you connect, and will be set back to whatever was after you disconnect from the SSH session. If, for same reason the script would exit before setting the title back, you’ll only need to launch it without arguments, and it will set the name to the default “Terminal” title.