Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Set tmux pane title to short hostname on ssh connections
# Make short hostname only if its not an IP address
__tm_get_hostname(){
local HOST="$(echo $* | rev | cut -d ' ' -f 1 | rev)"
if echo $HOST | grep -P "^([0-9]+\.){3}[0-9]+" -q; then
echo $HOST
else
echo $HOST| cut -d . -f 1
fi
}
__tm_get_current_window(){
tmux list-windows| awk -F : '/\(active\)$/{print $1}'
}
# Rename window according to __tm_get_hostname and then restore it after the command
__tm_command() {
if [ "$(ps -p $(ps -p $$ -o ppid=) -o comm=| cut -d : -f 1)" = "tmux" ]; then
__tm_window=$(__tm_get_current_window)
# Use current window to change back the setting. If not it will be applied to the active window
trap "tmux set-window-option -t $__tm_window automatic-rename on 1>/dev/null" RETURN
tmux rename-window "$(__tm_get_hostname $*)"
fi
command "$@"
}
ssh() {
__tm_command ssh "$@"
}
ec2ssh() {
__tm_command ec2ssh "$@"
}
@offby1

This comment has been minimized.

Copy link

offby1 commented Jul 3, 2018

I found that my tmux program was named tmux-2.1, not tmux, so I generalized things a bit by using case instead of if:

__tm_command() {
    case "$(ps -p $(ps -p $$ -o ppid=) -o comm=| cut -d : -f 1)" in
        tmux*)
            __tm_window=$(__tm_get_current_window)
            trap "tmux set-window-option -t $__tm_window automatic-rename on 1>/dev/null" RETURN
            tmux rename-window "$(__tm_get_hostname $*)"
            ;;
    esac
    command "$@"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.