tmux 快速参考
1. Core Concepts
tmux 是终端复用器,在服务器端运行。SSH 断开或本地电脑关机,tmux 内的程序继续运行。
三层结构:会话 Session(顶层容器)包含多个 窗口 Window(类似浏览器标签),每个窗口可分割为多个 窗格 Pane(独立终端区域)。
2. Installation
| Platform | Command |
|---|---|
| macOS (Homebrew) | brew install tmux |
| Ubuntu / Debian | sudo apt install -y tmux |
| CentOS / RHEL | sudo yum install -y tmux |
| Alpine Linux | apk add tmux |
3. Session Management
| Command | Action |
|---|---|
tmux new -s name | Create named session |
tmux ls | List all sessions |
tmux a -t name | Attach to existing session |
tmux new -A -s name | Attach or create |
tmux kill-session -t name | Kill session completely |
4. Key Bindings
Prefix key = Ctrl+a (press Ctrl+a, release, then press the following key)
| Key | Action | Key | Action |
|---|---|---|---|
| | Split vertically | " | Split horizontally |
Arrows | Navigate panes | q | Show pane numbers |
c | New window | d | Detach session |
n / p | Next / Prev window | & | Close current window |
1-9 | Select window | w | Window list select |
! | Break pane to window | z | Zoom / restore pane |
x | Close current pane | [ | Copy mode |
Ctrl+d | Exit tmux | ? | Show all bindings |
5. Remote Daemon Workflow
| Step | Action | Note |
|---|---|---|
| 1 | ssh user@server | Connect to server via SSH |
| 2 | tmux new -s work | Create tmux session |
| 3 | python train.py | Run task inside session |
| 4 | Ctrl+a d | Detach (keeps running) |
| 5 | exit | Safely disconnect SSH / close laptop |
| 6 | ssh user@servertmux a -t work | Reattach later |
6. Pane Management
| Action | Method | Note |
|---|---|---|
| Navigate panes | Ctrl+a o | Cycle through panes |
| Close current pane | Ctrl+a x | Prompts confirm, press y |
| Force kill pane | Ctrl+a :kill-pane | When pane is frozen |
| Zoom / restore | Ctrl+a z | Fullscreen / restore layout |
| Kill remote pane | tmux kill-pane -t 0:0.2 | Run from native terminal |
7. Text Copying
Recommended: set -g mouse off, keep native terminal mouse selection.
| Method | Operation |
|---|---|
| iTerm2 native (recommended) | Drag select → Cmd+c |
| Vi copy mode | Ctrl+a [ → v select → y copy |
| Option+mouse (fallback) | Hold Option while dragging, bypass tmux intercept |
8. Tips
Reload config
After editing
~/.tmux.conf, press Ctrl+a : and type source-file ~/.tmux.conf.Long-running task insurance
Use
nohup cmd > out.log 2>&1 & then disown, prevents process death if tmux closes unexpectedly.SSH keepalive
Add
ServerAliveInterval 60 to ~/.ssh/config to prevent idle disconnects.Cross-machine consistency
Sync local
~/.tmux.conf to remote via scp, keep key bindings consistent.