Strovent SystemsSign in
Reference

Keep your work after a disconnect with tmux, and attach automatically

How tmux keeps a session alive when SSH or the app drops, one command that creates or reattaches, and how to run it over SSH, over Mosh and at login.

When a connection drops, the shell on the host usually loses its terminal and ends the programs that were running in it. tmux keeps them running.

What tmux does

From the tmux manual: each session is persistent and survives accidental disconnection, such as an ssh connection timeout, or an intentional detach with Ctrl+b d. The sessions are managed by a single server on the host, and a client shows one of them on screen. Once all sessions are killed, tmux exits.

So the work lives in the tmux server, not in your SSH connection. After a drop, log in again and reattach:

tmux attach

One command: create it or reattach

new-session -A behaves like attach-session if a session with that name already exists, and creates it if not. Use the same command every time:

tmux new-session -A -s main

-s main names the session main.

Over SSH and Mosh

A screen program needs a terminal, so SSH must request one when you give it a command. The ssh manual says -t forces pseudo-terminal allocation, for running screen-based programs on a remote machine:

ssh -t [email protected] tmux new-session -A -s main

Over Mosh, put the command after --:

mosh [email protected] -- tmux new-session -A -s main

The Mosh manual's synopsis is mosh [options] [--] [user@]host [command...]. With Mosh the connection survives brief drops by itself; tmux also keeps the work after you close the client. See Mosh or SSH?.

Start it at login

To enter tmux every time you log in over SSH, add this to the shell's startup file on the host, for example ~/.profile for a POSIX shell:

if [ -n "$SSH_CONNECTION" ] && [ -z "$TMUX" ] && command -v tmux >/dev/null; then
  exec tmux new-session -A -s main
fi

Try it in a second session before you log out of the first, in case of a typo.

If tmux is gone after you log out even though you detached, systemd may be ending your login session's processes. See tmux killed on SSH logout: systemd KillUserProcesses and linger.

Start it from a script in the app

You can make the app type the command for you with a script that runs when the session connects: a Wait text step on the shell prompt, a Type step with tmux new-session -A -s main, and a Key step for Enter. See Scripts and macros and Auto-connect and auto-run.

Sources

Spotted a mistake? Email [email protected].