Keeping a command running after you close SSH: tmux and screen

The short answer: when you close the SSH window, or the connection drops, the system ends the programs that were running in it. tmux (and screen) solve that: they open a session that keeps running on the server even without you, and that you return to whenever you like.

tmux, the essentials

1 Install it, if it is not there: sudo apt install tmux (Ubuntu and Debian).
2 Open a named session: tmux new -s work. Run the slow command in it (a big copy, a migration, an rsync).
3 Leave without closing it: press Ctrl+b, release, then d. You are back at the normal command line and the session keeps running.
4 See the sessions that exist: tmux ls.
5 Go back to it, even after closing SSH and logging in again: tmux attach -t work.
6 End it when done: type exit inside it, or tmux kill-session -t work from outside.

The same with screen

To screen
Open a session screen -S work
Leave without closing Ctrl+a, release, and d
See the sessions screen -ls
Go back to one screen -r work

What about nohup?

For a single command you do not need to watch afterwards, nohup is enough: nohup ./my-script.sh &. The output goes to the file nohup.out. But you cannot “walk back into” it. To watch it live, use tmux.

A tmux session does not survive a server restart. For an application that must always be running, and come back by itself after a restart, do not use tmux: use a system service (systemd). See FastAPI on a VPS, which shows an example.
If your SSH connection drops often, see Common VPS and Cloud errors. And for tasks that run at set times, do not use sessions: see Cron jobs.

Have a long task on a VPS and not sure how to leave it running safely? Open a ticket describing what you want to do.

Open a support ticket

SEE ALSO

Cron jobs: what they are for and how to create one

FastAPI on a VPS: uvicorn workers, proxy headers and a service that restarts

How to see what is using CPU, memory and disk on your VPS

Common VPS and Cloud errors: SSH, memory, disk and reboots

RECOMMENDED PRODUCT

VPS server with root access

Resources of your own, the OS you choose, reinstall whenever you like. from $8.39/mo (3-year plan, with coupon)

See plans
  • 0 Users Found This Useful
Was this answer helpful?