Use tmux with SSH to maintain persistent sessions that survive network disconnections. Either run ssh user@host
then start tmux on the remote server, or use ssh user@host -t tmux
to directly attach to a session. If disconnected, simply reconnect and reattach with ssh user@host
followed by tmux attach
.
ssh user@host -t tmux attach
Combining tmux with SSH creates a resilient remote workflow that continues running even when your connection drops. This approach is invaluable for unstable networks, long-running processes, and remote development.
# Step 1: Connect to remote server $ ssh user@hostname # Step 2: Start a new tmux session on the remote machine $ tmux # If disconnected, reconnect and reattach $ ssh user@hostname $ tmux attach
# Directly start or attach to tmux on connection $ ssh user@hostname -t tmux # Specifically attach to an existing session $ ssh user@hostname -t tmux attach # Create a new named session if none exists $ ssh user@hostname -t tmux new -s mysession # Attach to specific session $ ssh user@hostname -t tmux attach -t mysession
The -t
flag forces SSH to allocate a pseudo-terminal, which tmux requires.
# Create a session if none exists, or attach to existing one $ ssh user@hostname -t tmux new-session -A -s mysession
The -A
flag makes tmux attach if the session exists or create it if it doesn't.
If you run tmux locally and on remote servers, you'll have nested tmux sessions. Use different prefix keys to avoid confusion:
# On your local machine's ~/.tmux.conf set -g prefix C-a unbind C-b bind C-a send-prefix # On the remote machine's ~/.tmux.conf # Keep the default Ctrl+b prefix
Now use Ctrl+a for your local tmux and Ctrl+b for the remote tmux.