Shell – Don’t nest tmux in a remote ssh shell

moshshellsshtmux

I've set up the .zshrc of my user account on all of the hosts to which I connect to automatically start tmux on login as long as it's not already running.

if [ -z "$TMUX" ]; then
tmux attach -d || tmux new
fi

This works well until I ssh (or mosh) into my own account on a remote host from within a tmux session on the local host. Since the $TMUX macro isn't passed from the local host to the remote, tmux launches on the remote host and I now have two nested tmux sessions.

Is there a way to avoid this while keeping the auto-launching behaviour? Ideally I'd like the remote shell to know that it's being launched from within a tmux session on the host that is connecting and to not launch a second tmux instance.

I've already tried checking $TERM in the remote shell but it is always xterm-256color regardless of whether it is running within a tmux session on the local machine.

Best Answer

Thanks to @mark-plotnick 's comment I think I have solution that works for me.

On the remote host, add to /etc/ssh/sshd_config:

AcceptEnv TMUX

On the local host, add to ~/.ssh/config:

Host * SendEnv TMUX

Now the value of the $TMUX env variable is sent to the remote host, and tmux no longer launches when the value is non-blank.

I don't mind making the server-side change but I wish I didn't have to edit every client ~/.ssh/config so I'm open to additional suggestions.

Related Question