How to work with nested tmux sessions?

Quick Answer

To work with nested tmux sessions (tmux inside tmux), use different prefix keys for each level. Set your local tmux to use Ctrl+a and keep the remote session with the default Ctrl+b. Alternatively, press the prefix key twice (Ctrl+b Ctrl+b) to send the prefix to the inner session.

set -g prefix C-a

Detailed Explanation

Nested tmux sessions occur when you run tmux inside another tmux session, typically when connecting to a remote server that's also running tmux. Without proper configuration, both tmux instances will use the same prefix key, making it difficult to control the inner session.

Method 1: Different Prefix Keys

The most common approach is to use different prefix keys for local and remote tmux sessions:

# In your local ~/.tmux.conf
set -g prefix C-a
unbind C-b
bind C-a send-prefix

# Keep the default Ctrl+b prefix on remote machines

With this setup, use Ctrl+a for commands to your local tmux and Ctrl+b for the remote tmux. This clear separation makes nested sessions much easier to manage.

Method 2: Sending the Prefix Key

If you want to keep the same prefix key for both sessions, you can press the prefix key twice to send it to the inner session:

# In both local and remote ~/.tmux.conf
bind C-b send-prefix

With this configuration:

  • Ctrl+b command will send commands to the outer (local) tmux
  • Ctrl+b Ctrl+b command will send commands to the inner (remote) tmux

Visual Indicators for Nested Sessions

It's helpful to have visual cues showing which tmux level you're controlling. Add these to your configurations:

# Local tmux (level 1) - Green status bar
# In local ~/.tmux.conf
set -g status-style "bg=green,fg=black"

# Remote tmux (level 2) - Red status bar
# In remote ~/.tmux.conf
set -g status-style "bg=red,fg=white"

You can also include the hostname in the status bar to further distinguish sessions:

# Add hostname to status bar
set -g status-right "#H [#S]"

Pro Tip

Create a special key binding that allows you to send a specific sequence to the inner tmux session without changing your prefix:

# Add to your local ~/.tmux.conf
bind-key b send-keys C-b

With this configuration, you can press Ctrl+a b to send Ctrl+b to the inner session, which is often more convenient than pressing the prefix twice.

Working with SSH and Nested Tmux

When using SSH with tmux, you can automate the process of connecting to a remote tmux session:

# Add to your .bashrc or .zshrc
function ssh-tmux() {
  ssh -t "$1" "tmux attach || tmux new -s remote"
}

Now you can connect to a remote server and automatically attach to a tmux session with:

ssh-tmux user@hostname

This creates a consistent nested tmux environment where you're always using local and remote sessions in the same way.