Sessions: create, detach, attach

tmux · Essentials · 8 min

Detach/attach is tmux's killer feature: work survives closed laptops and dropped SSH connections.

When you run tmux, it starts a background server (if none is running) and creates a session inside it, then attaches your terminal as a client. Programs run inside the server, not inside your terminal window.

That means you can detach (C-b d, or close the terminal, or lose your SSH connection) and every program in the session keeps running. Later you attach again and find everything exactly as you left it, scrollback included.

The shell commands to know:

  • tmux new -s work creates a session named work (names beat the default numbers).
  • tmux ls lists sessions.
  • tmux attach -t work (or tmux a -t work) reattaches.
  • tmux new -A -s work attaches to work if it exists, otherwise creates it: ideal for scripts and shell aliases.
  • tmux kill-session -t work ends a session and everything in it.

A session ends when its last shell exits; the server exits when it has no sessions left. The typical remote workflow: ssh server, tmux new -A -s main, start a long build or migration, detach, log out, come back tomorrow and attach.

Example

tmux new -s build        # new session named 'build'
#   ... start a long job, then C-b d to detach
tmux ls                  # build: 1 windows (created ...)
tmux attach -t build     # back where you left off
tmux new -A -s main      # attach to 'main' or create it
tmux kill-session -t build

Remember

  • Programs run in the tmux server, so they survive detaching
  • tmux new -s name, tmux ls, tmux attach -t name
  • tmux new -A -s name = attach or create

Watch out for

  • Starting tmux inside tmux by accident (e.g. an alias in .bashrc), which nests sessions; check $TMUX first.

Check yourself

  1. Your SSH connection drops while a job runs inside tmux on the server. What happens to the job?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: github.com/tmux/tmux/wiki/Getting-Started

Sessions: create, detach, attach · tmux · Topolearn