I like having tmux or screen start automatically when I connect to a machine, and if possible I like having the previous detached session restored. I think it was this post which inspired me at the time, at least it sounds familiar.

Be that as it may, there are a couple of things which I’ve modified:

  1. on machines which periodically clear out /tmp I want tmux’ Unix domain socket directory moved to a more permanent location, so I set TMUX_TMPDIR accordingly.
  2. When using rsync -e ssh to a machine, a pty is not requested, and so I circumvent the tmux magic.

Here’s the tail of my ~/.profile:

if [[ -n "$SSH_TTY" ]]; then
	export TMUX_TMPDIR=$HOME/tmp
        sname="ssh-$(hostname | cut -d. -f1)"
        if [[ -z "$TMUX" ]] && [ "$SSH_CONNECTION" != "" ]; then
            exec tmux new-session -A -s $sname
        fi
fi

So when I login via SSH tmux is started with a new session or, if the session exists, it attaches to that existing session. The login shell execs tmux, so I’m logged out automatically when I detach from tmux.

I’d have liked to exec the tmux but I can’t do it with the ||. Thanks to Daniel Néri and Ivan Tomica for the idea on using the -A flag.

Thanks to Raf Czlonka, we get a POSIX-compliant version which ought to work for most shells, and it does away with mixing POSIX and non-POSIX test, uses hostname -s which should work on most systems, and simplifies the if:

test -n "$SSH_TTY" && {
        TMUX_TMPDIR=$HOME/tmp
        export TMUX_TMPDIR
        test -d $TMUX_TMPDIR || mkdir -p $TMUX_TMPDIR
	test -z "$TMUX" -a -n "$SSH_CONNECTION" &&
                exec tmux new-session -A -s "ssh-$(hostname -s)"
}
tmux and SSH :: 28 Apr 2019 :: e-mail