HOW TO : Launch tmux on SSH login

I’m terrible at remembering to start tmux when I SSH into servers. Then invariably, my connection drops mid-compile or during a long-running test, and I lose everything :-(.

The solution? Just make tmux start automatically when you SSH in. Here’s how.

The Problem

You SSH into your server, start working, and then:

  • Your WiFi hiccups
  • Your laptop sleeps
  • You close the terminal by accident

And poof—all your work is gone. tmux solves this by keeping your session alive on the server, but only if you remember to actually start it.

The Solution

Add a simple check to your ~/.bashrc that auto-launches tmux when you connect via SSH.

# Auto-launch tmux on SSH connection
# To skip: either detach from tmux (Ctrl+b, then d) or set TMUX_SKIP=1 before connecting
# Example: TMUX_SKIP=1 ssh user@host
if [[ -n "$SSH_CONNECTION" ]] && [[ -z "$TMUX" ]] && [[ -z "$TMUX_SKIP" ]] && command -v tmux &> /dev/null; then
tmux attach-session -t default || tmux new-session -s default
fi

Add this to the end of your ~/.bashrc file.

How It Works

The script checks four conditions before launching tmux:

  1. -n "$SSH_CONNECTION" — Are you connecting via SSH? (Doesn’t trigger for local terminal sessions)
  2. -z "$TMUX" — Is tmux not already running? (Prevents tmux-inception)
  3. -z "$TMUX_SKIP" — Did you explicitly skip tmux? (More on this below)
  4. command -v tmux — Is tmux actually installed?

If all checks pass, it tries to attach to an existing session named “default”. If that session doesn’t exist, it creates one.

Skipping tmux When Needed

Sometimes you just want a plain shell—for quick commands, debugging, or whatever. Two ways to skip:

Option 1: Set an environment variable

TMUX_SKIP=1 ssh user@server

Option 2: Detach after connecting

Ctrl+b, then d

This drops you to a regular shell without killing the tmux session.

Why This Setup?

  • Named session: Using default as a session name makes it easy to reconnect
  • Attach-or-create: The || operator means it’ll create the session only if it doesn’t exist
  • No exec: Some examples use exec tmux ... which replaces your shell entirely. I prefer not doing that—it makes skipping harder and can be annoying for scripted SSH commands

That’s it. Now you can SSH in, disconnect whenever, and pick up right where you
left off. No more lost work from dropped connections.