How to send commands when opening a tmux session inside another tmux session?

A typical situation may be:

$ tmux
  [0] $ ssh example.com
      $ tmux attach
        [0] $ 

I open a tmux session, then ssh in to a server and attach to an existing tmux session. At this point I have one tmux session inside another. How do I send commands to the inner tmux session?

Note: Both tmux sessions have the same key bindings.


Solution 1:

The send-prefix command can be used to send your prefix keystroke to (the process running in) the active pane. By default, the prefix is C-b and C-b is bound to send-prefix (so that hitting it twice sends a single C-b to the active pane). This is just what we need to access the bindings of the inner tmux instance.

The first C-b is captured by the “outer” tmux instance as its prefix key. The second one is captured by the “outer” tmux instance and triggers its C-b binding (send-prefix). This sends a C-b to the outer instance’s active pane. The process running in this pane is (ultimately, through an ssh instance) the “inner” tmux instance. It captures the C-b as its prefix key. Now your next keystroke will be passed through the outer tmux instance and captured by the inner one to trigger a binding.

To trigger the c binding (new-window) in a second-level instance of tmux, you would type C-b C-b c. For a third-level instance of tmux you would type C-b C-b C-b C-b c.

This doubling for each level can be annoying if you are commonly dealing with multiple layers of tmux. If you can spare some other key, you could make a non-prefixed binding to make things (possibly) easier to type:

bind-key -n C-\ send-prefix
bind-key -n C-^ send-prefix \; send-prefix

Create new window in second-level tmux: C-\ c
Create new window in third-level tmux: C-^ c (or C-\ C-\ c)


If you have a limited number of tmux commands that you want to (easily) send to the lower-level tmux instances, you might instead use send-keys to create some specific bindings (possibly just in your top-level tmux instance):

bind-key C-c  send-keys C-b c
bind-key C    send-keys C-b C-b c

Create new window in second-level tmux: C-b C-c
Create new window in third-level tmux: C-b C

Solution 2:

To access the inner, hold control and hit B twice.

Solution 3:

EDIT:

I do NOT recommend use C-q as a bind-key, as it is a default control-key command for

un-freezes the screen and lets screen display continue

A situation happens here, and @Paschalis provides a solution:

if it happens to be twice unlucky (a remote tmux session with C-q as prefix): Type Cltr-q, then :, and enter in tmux: send-keys C-q

Below it is the answer:


To make it simple, add the below line in your ~/.tmux.conf

bind-key -n C-q send-prefix

Then you can directly use C-q as bind-key for your remote tmux.