Set tmux pane title on SSH connections

I am frequently connecting to several servers over SSH at once and like to use tmux to organize those different sessions. To be able to keep track which pane is which server I am using the following function in my .bashrc file to display the machine name in tmux’s pane title.

ssh() {
if [ "$(ps -p $(ps -p $$ -o ppid=) -o comm=)" = "tmux" ]; then
tmux rename-window "$(echo $* | cut -d . -f 1)"
command ssh "$@"
tmux set-window-option automatic-rename "on" 1>/dev/null
else
command ssh "$@"
fi
}

https://gist.github.com/florianbeer/ee02c149a7e25f643491

tmux

4 comments

  1. Sure!
    The first line overwrites the “ssh” command in your shell. The part after “if” basically tries to find out if you are inside a tmux session. If it finds out that this is the case, it will rename the current window with the first part (up until the first dot) of the fully qualified domain name you are connecting to. After this it just executes the normal “ssh” command and reactivates tmux’s automatic window renaming. The else part just skips the whole window renaming, since you’re not in a tmux session.

    I know the part about using the start of the FQDN until the first dot isn’t particularly clever, but it works for me. All of my servers get a primary DNS entry of $hostname.42dev.net so with this method I’ll always have the hostname as a window title.

  2. Looks good! Thanks for the snippet.
    I altered it for my needs by changing the cut command to use a delimiter of @ and picked off the 2nd field:

    tmux rename-window “$(echo $* | cut -d @ -f 2)”

    This is good for my (and perhaps others’) applications where your ssh calls are of the form `ssh username@machineAddress. It’ll change the pane name to machineAddress (the IP, if that’s how to access it).

    Cheers,

  3. I do this, which is good for IP addresses as well, cutting off username.

    tmux rename-window “$(echo “${@: -1}” | rev | cut -d ‘@’ -f1 | rev )”;

Leave a Reply to ghost21 Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.