How to Keep a Command Running After You Disconnect (tmux for Beginners)

Start a big download or a long backup over SSH, close your laptop, and the job dies with the connection. tmux fixes that. It runs a terminal inside the server that keeps going whether you're connected or not. You detach, go for lunch, reconnect, and pick up exactly where you left off.
Quick reference
| Action | Command / keys |
|---|---|
| Install | sudo apt install tmux -y |
| Start a session | tmux new -s backup |
| Detach (leave it running) | Ctrl + B, then D |
| List sessions | tmux ls |
| Reattach | tmux attach -t backup |
| End a session | type exit inside it |
1. Start a session
tmux new -s backup
The -s backup gives it a name so you can find it later. A green bar appears at the bottom — you're now inside tmux. Run whatever you like:
rsync -avz --progress /data/ /mnt/backup/
2. Detach
Press Ctrl + B, let go, then press D. You're back at your normal prompt and the rsync is still running in the background. Close the laptop, go home, whatever.
Every tmux shortcut starts with Ctrl + B (the prefix) followed by a key.
3. Come back
tmux ls
tmux attach -t backup
There it is, still running or finished, with all its output. If there's only one session, tmux a is enough.
4. Finish
When you're done with the session, type exit inside it. The green bar disappears and the session is gone.
The other three shortcuts worth knowing
- Ctrl + B, C — new window (a second tab inside the session). Ctrl + B, N / P move between them.
- Ctrl + B, % — split the screen side by side. Ctrl + B, " splits top and bottom. Ctrl + B, arrow moves between panes.
- Ctrl + B, [ — scroll mode. Use Page Up, arrows or / to search; q to leave. (Scrolling normally with the mouse doesn't work inside tmux unless you enable it.)
Enable mouse scrolling and pane clicking permanently:
echo "set -g mouse on" >> ~/.tmux.conf
Alternatives
- screen — older, same idea. screen -S name, detach with Ctrl + A, D, reattach with screen -r.
- nohup — for a single command you'll never need to look at: nohup ./long-job.sh &. Output goes to nohup.out.
- systemd service — for things that should always run, make a service instead (tutorial 13).
Troubleshooting
"sessions should be nested with care." You ran tmux inside tmux. Type exit or detach from the inner one.
Ctrl + B does nothing. You're not inside tmux — check for the green bar. Or another program (Vim, nano) has the keys; leave it first.
Can't see old output after reattaching. Use Ctrl + B, [ and scroll up. tmux keeps the last 2,000 lines by default; raise it with set -g history-limit 10000 in ~/.tmux.conf.
Copy and paste looks wrong. Hold Shift while selecting with the mouse to use the terminal's own copy instead of tmux's.
Wrapping up
tmux new -s name, run the job, Ctrl + B, D to walk away, tmux attach to come back. Once you've lost a six-hour job to a dropped connection you'll never start a long command without it.
