Altering the terminal title bar in Mac OS X

After one year of owning a MacBook Pro, I finally got around to fix my precmd() ZSH-hack to really make the current directory and stuff appear in the title bar of Terminal.app and iTerm.app.

This is the code to add to your .zshrc:

case $TERM in
    *xterm*|ansi)
		function settab { print -Pn "e]1;%n@%m: %~a" }
		function settitle { print -Pn "e]2;%n@%m: %~a" }
		function chpwd { settab;settitle }
		settab;settitle
        ;;
esac

settab sets the tab contents in iTerm and settitle does the same thing for the title bar both in Terminal.app and iTerm.

The sample also shows the variables ZSH replaces in the strings (the parameter -P to print lets ZSH do prompt expansion. See zshmisc(1) for a list of all variables): %n is the currently logged on user, %m the hostname up until the first dot and %~ is displaying the current directory or ~ if you are in $HOME. You can certainly add any other environment variable of your choice if you need more options, but this more or less does it for me.

Usually, the guides in the internet make you use precmd to set the title bar, but somehow, Terminal wasn’t pleased with that method and constantly kept overwriting the title with the default string.

And this is how it looks in both iTerm (above) and Terminal (below):