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

Reference - Thanks To Kamil Maciorowski

Intro

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).

TMUX

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

First make sure that you path is set up to search in the ~/bin-folder. Run echo $PATH and look for /home//bin. if it’s not there you can use /usr/local/bin. Create the ~/bin-folder if it’s not there and it’s in the $PATH.
Create the ~/bin/_tmux_duplicate_pane-file (or /usr/local/bin/_tmux_duplicate_pane) and add:

#!/bin/bash
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"
name="${args[0]}"
args=("${args[@]:1}")

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

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

bind-key -T prefix u run-shell _tmux_duplicate_pane

Conclusion

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