How to set up tmux to duplicate a pane, even when logged in to a remote server

Reference - Thanks To Kamil Maciorowski


Often, when I’m working on a server, I want to open a new pane on the same server. But it’s troublesome to reconnect, so I looked into ways to duplicate my connection without login in again. Here’s how I have configured ssh and tmux to do this!

SSH Multiplexing

First I set up ssh multiplexing
Create the folder ~/.ssh/sessions/
Then, in your ~/.ssh/config-file add:

### Multiplexing ###
Host *
    ControlMaster auto
    ControlPath ~/.ssh/sessions/%C
    ControlPersist 1h

This sets ssh to handle your sessions in a file, so that when you connect to the same server twice it will use the same session (so you don’t have to log in again).


To set up tmux, we have to create a scriptfile in $PATH and add and bind it in tmux.

Create the ~/bin-folder.
Create the ~/bin/_tmux_duplicate_pane-file and add:

set -e

pid="$(tmux display-message -p '#{pane_pid}')"
pid="$(ps -o tpgid:1= -p "$pid")"
dir="$(readlink -f "/proc/$pid/cwd")"
cd -- "${dir:?}"
exe="$(readlink -f "/proc/$pid/exe")"
readarray -d '' args <"/proc/$pid/cmdline"

tmux split-window "[email protected]" -c "$dir" bash -c "exec -a ${name@Q} ${exe@Q} ${args[*]@Q}"

To bind it in tmux, add this to the ~/.tmux.conf-file:

bind-key -T prefix u run-shell _tmux_duplicate_pane


When this is set up, you should be able to log into a server over ssh, press the tmux prefix and u, and continue in a new pane with the same session.
If not, LET ME KNOW!