Is there a way to find out the pane index of a particular pane in Tmux?
I know I can run something like:
tmux display-message -p "#{pane_index}"
but that only works on the active pane. I want it to work for whatever pane it's run in. Normally of course it's hard to run a script in a pane that's not the active pane, but you can if you use the :set-window-option synchronize-panes
to sync input between all panes.
How would I use this?
In my job I need to connect to multiple identical servers in a load balancer at the same time, which I do with Tmux panes. I normally turn on the synchronize panes feature to allow me to have whatever I type identically sent to each pane at the same time. This works great.
The thing I find is that I'd like to connect to the servers and do something unique to each pane sometimes, using the same "pane index" each time. For example, I'd run a command like so:
ssh NODE_$(get_pane_number)
which, when synchronized and run in each pane, would run the following commands in a window with 4 panes:
ssh NODE_0
in pane 0
ssh NODE_1
in pane 1
ssh NODE_2
in pane 2
ssh NODE_3
in pane 3
I could of course script this, but that would only work well before I started synchronizing inputs. There are times when I'd like to do this after I've started synchronizing inputs as well.
Best Answer
tmux (since v1.5) provides TMUX_PANE in the environment of the process it launches for a pane; each new pane gets a server-unique value. So, assuming that TMUX_PANE is available in your environment, then this should do what I think you want:
The
${…:?}
syntax in a Bourne-like shell prevents the expansion of missing or empty parameters. In this case, an empty expansion would fall back to the default of using “the currently active pane”, which is usually—but not always—the same as “this pane” (they will likely differ if the command’s tty is not the one that tmux started; e.g. because of using script or expect, et cetera).