Terminal Tab Title after SSH Session

In Mac OS X (I'm on 10.6.8, though I believe other versions are the same) ssh'ing into a remote machine changes the title of the current tab in Terminal. Annoyingly, when I disconnect from the remote machine, either explicitly with exit or via a timeout, the title of the tab doesn't change back to what it was.

On an almost daily basis this nearly causes me to suffer a heart attack, when I'm typing away performing some command or other, only to see out of the corner of my eye that the tab is still named user@remotehost. I'm a cautious user that always tends to pwd etc to confirm my location before doing anything, yet it still catches me in a moment of panic when I'm doing DROP DATABASE x and I see the remote host name in the tab.

Long story short, is there a way to revert this title when disconnecting from a remote host, or do I have to stick with opening a new tab every time I disconnect, to reset the title?


Add a PROMPT_COMMAND to your .bash_profile

export PROMPT_COMMAND="echo -ne '\033]0;${USER}@${HOSTNAME}\007';$PROMPT_COMMAND"

The PROMPT_COMMAND gets executed every time the prompt is displayed.

Please note that we include the existing PROMPT_COMMAND environment variable, such that we do not lose any existing settings (i.e. update_terminal_cwd).


To make @s01ipsist's solution work with ZSH (new shell on macOS), you can add this to ~/.zshrc:

export PROMPT_COMMAND="echo -ne '\033]0;${USER}@${HOST}\007';$PROMPT_COMMAND"
precmd() { eval "$PROMPT_COMMAND" }

Here's what you'll need to paste into your .bash_profile file. This is far cleaner and takes the approach what Apple does when it updates your current working directory. The check for the variable update_term_title is already present is not really necessary (as nobody calls bash -- login), but just present as a guard.

if [ -z "$INSIDE_EMACS" ]; then
    # Update the terminal title on every prompt shown
    update_term_title() {
        # Print user@short-hostname once SSH quits.
        echo -ne "\033]0;${USER}@${HOSTNAME%%.*}\007"
        # Or ${HOSTNAME} if short host names aren't your taste
        # Or echo -ne "\033]0;\007" if you don't want anything.
    }
    # Check to see if update terminal title is present?
    if ! echo $PROMPT_COMMAND | grep -q update_term_title
    then
       # This function is not found in PROMPT_COMMAND, add it
       PROMPT_COMMAND="${PROMPT_COMMAND:+$PROMPT_COMMAND; }update_term_title"
    fi
fi