Setting terminal title to ssh hostname

For my daily work, I frequently need to log into servers using SSH. Typically I’m using a jumphost with tmux, so I can have multiple windows and easily reconnect during or after my commute. One of my annoyances was that I was having problems seeing which servers I’m logged in to. Tmux will helpfully set the window title to the command which was run last. But in my case, the only command I’d ever run from my jumphost would be SSH, so I’d just end up with a number of windows titled ‘SSH’, which isn’t very helpful.

The common wisdom for this situation is to add some ANSI codes to your .bashrc on the SSH target. Unfortunately this method is unacceptable for me, as I can’t change the server configurations. So all of the work should be done on the jumphost. So, instead of responding to a login from .bashrc, I wrapped the ssh command on my jumphost:

function ssh {
    local saved_args="$@"
    local title=""

    # ssh is sometimes used as part of command completion
    # in that case setting the terminal title isn't desirable
    # During bash completion $COMP_LINE is filled, so exclude
    # that.
    if [ -z "$COMP_LINE" ] ; then
        while [[ -n "$1" && -z "$title" ]] ; do
            local arg="$1"
            shift
             if [[ "$arg" =~ ^[^-] ]] ; then 
                 title="${arg%%.*}"
            fi
         done
    fi

    # If a title was found, set the terminal title.
    if [ -n "$title" ] ; then
        printf "\033k%s\033\\" "$title"
    fi

    /usr/bin/ssh $saved_args
    local status=$?

    # ssh is done. Restore the terminal title
    if [ -n "$title" ] ; then
        printf "\033k%s\033\\" "$(hostname -s)"
    fi

    return $status
}

printf "\033k%s\033\\" "$(hostname -s)"
Back To Home

Comments