How to Keep a Linux Command Running in the Background Using tmux

When you are managing a remote Linux server via an SSH (Secure Shell) connection, you face a critical danger: session fragility. If you trigger a massive database backup script or start a video rendering job that will take six hours to complete, that command is inextricably tied to your active SSH window. If your home Wi-Fi drops for even a single second, or your laptop goes to sleep, the SSH connection breaks. When the connection dies, Linux instantly kills your running script, forcing you to start the six-hour process all over again. You can completely prevent this catastrophe by using a terminal multiplexer called tmux.

What is Tmux?

Tmux creates a persistent, virtual terminal session running in the background of the server. You can “attach” your screen to this virtual session to see what is happening, and then safely “detach” your screen and walk away. The virtual session, and everything running inside it, will continue operating flawlessly even if you completely turn off your local computer.

If you do not have it installed, you can usually grab it via your package manager (e.g., sudo apt install tmux).

How to Start a Persistent Session

  1. Log into your server via SSH as normal.
  2. To create a new, named virtual session (let’s call it “backup”), type the following command and press Enter:
    tmux new -s backup
  3. Your screen will briefly refresh, and a green status bar will appear at the very bottom of your terminal. You are now safely inside the tmux session.
  4. Run your long script or command (e.g., ./massive_backup.sh).

How to Detach and Reattach

Now that your script is running, you want to leave safely without killing it.

  1. To detach from the session, you must press a specific keyboard combination. Hold Ctrl and press B. Release both keys. Then, press D (for detach).

The green bar will disappear, and your terminal will print [detached (from session backup)]. Your script is now safely running in the background. You can type exit to close your SSH connection, close your laptop, and go to bed.

The next morning, to check on your script’s progress, simply SSH back into the server and type:

tmux attach -t backup

Your screen will instantly snap back into the virtual session, showing you exactly where the script left off, allowing you to review the final logs.

Leave a Reply

Your email address will not be published. Required fields are marked *

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.

Receive our best articles and tips delivered straight to your inbox.