How to reset iTerm2 Window/Tab Title when disconnecting from remote host? I have my bash_profile on my Mac and the remote computers I connect to setup to automatically put the hostname in the window's (or tab's) title area.

A bash shell on my local machine



A remote host name "Socrates"; also a bash shell.



The problem is, when I exit (and disconnect) from the remote host, the window title stays with the host name of the remote.  So, in effect, I'm on the local Apple bash shell with the remote name.  To fix it, I do one of the following:


close the window and open a new one
re-source the .bash_profile (. ~/.bash_profile)
create a new sub shell by issuing the command bash (not desirable at all)


How can I have this done automatically so that when I exit a remote shell, the title goes back to the original host name so I know what host I'm actually connected to?

Note, the previously asked question, Terminal displays directory of previous SSH location even when not running SSH didn't adequately address the issue because the solution was to modify .bash_logoff which only worked for login shells.
The solution to this problem is solved by using Terminal Control Codes (Esc 22 and 23) and  placing four simple lines in .bashrc of the remote host:

# ~/.bashrc
#
# Set the Terminal Title

echo -ne "\033[22;0t"                     #Save Title on Stack
echo -ne "\033]0;${HOSTNAME}\007"         #Set New Title

trap 'echo -ne "\033[23;0t"'  EXIT        #Reset Title Window


How This Works

By using the Terminal Escape Sequence Codes 22 and 23, we can save and retrieve the original title.  The trap function (man bash) will execute a command when a signal is received; in this case upon exit.

Now, when I exit (terminate) the remote host, the title reverts back to the proper host name.

Why .bashrc?

I want to have this available to me whether I log into the host from a remote machine (most common) or when I am local to it.  .bash_profile is read for an interactive login shell and .bashrc is read for an interactive, non-login shell (local) is started.

To ensure that this is the same for both conditions, I include the following in my .bash_profile:

# run a .bashrc file if it exists.

test -f ~/.bashrc &amp;&amp; . ~/.bashrc