Get pane # of each pane in a window from a script?

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:

tmux display -pt "${TMUX_PANE:?}" '#{pane_index}'

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).


You can get all pane index as well as many other information about the panes with

tmux list-panes -a

See tmux(1) FORMATS to get a list of information you can get and work with.


Building up on the two proposed solutions, I found this function to work for me:

I=$(tmux list-panes -a | grep $TMUX_PANE 2>/dev/null | awk -F: '{print $2}' | awk -F. '{print $2}')

or the same thing starting with index=1

I=$(($(tmux list-panes -a | grep $TMUX_PANE 2>/dev/null | awk -F: '{print $2}' | awk -F. '{print $2}') + 1))

It's not the prettiest but it works and I can drop it in my .bashrc and just use $I whenever I need

Tags:

Tmux