tmux: keep your terminal work alive over SSH
If you work on a remote machine over SSH, you have probably lost work to a dropped connection. A build dies halfway, a long-running script stops, or you close the laptop lid and everything is gone. tmux fixes that.
What tmux is
tmux is a terminal multiplexer. It runs a server in the background that holds your terminal sessions. Your terminal window is just a client attached to that server. When the client goes away, the sessions keep running, and you can attach again later from any terminal.
It also lets you split one terminal window into several panes and keep several windows open, like tabs.
The three ideas
- Session: a named workspace. You might have one called
mainand another calledbuild. - Window: like a tab inside a session.
- Pane: a split inside a window. Each pane runs its own shell or program.
The daily workflow
On the remote machine:
tmux new -A -s main
This attaches to a session called main, or creates it if it doesn’t exist. Start your build, dev server or editor. When you are done for now, press Ctrl-b then d to detach, or just close the terminal. Next time, run the same command and you are back exactly where you left off.
Check what is running with tmux ls.
Keys worth learning first
Every command starts with the prefix, Ctrl-b. Press it, release it, then press the next key.
| Keys | What it does |
|---|---|
Ctrl-b d |
Detach from the session |
Ctrl-b c |
New window |
Ctrl-b n / p |
Next / previous window |
Ctrl-b % |
Split left and right |
Ctrl-b " |
Split top and bottom |
Ctrl-b + arrow |
Move between panes |
Ctrl-b z |
Zoom a pane to full screen, and back |
Ctrl-b s |
Browse sessions and windows |
Ctrl-b [ |
Scroll and copy mode (q to leave) |
Ctrl-b ? |
List every key binding |
A small config
tmux reads ~/.tmux.conf when its server starts. This is enough to begin with:
set -g mouse on # scroll and click panes
set -g base-index 1 # number windows from 1
setw -g pane-base-index 1
set -g history-limit 50000 # more scrollback
set -sg escape-time 10 # no lag on Esc
# open splits and windows in the current directory
bind % split-window -h -c "#{pane_current_path}"
bind '"' split-window -v -c "#{pane_current_path}"
bind c new-window -c "#{pane_current_path}"
# reload the config with Ctrl-b r
bind r source-file ~/.tmux.conf \; display "Reloaded"
The config is only read when the server starts, so reload it with Ctrl-b r or restart tmux after editing.
When it is worth it
tmux earns its place when you work over SSH, run long builds, or want logs visible next to a shell. It is less useful on a local machine where your terminal app already has tabs and splits.
One caution: running tmux inside tmux gets confusing, because both want the same prefix key. If you use tmux locally and remotely, change the prefix on one of them.
Where to go next
The official wiki at github.com/tmux/tmux/wiki has a Getting Started guide, an FAQ and a Recipes page. man tmux is the full reference.