Jon Trainor
Jon Trainor

Reputation: 281

How to get the active tmux window's name?

I want to write a script that gets the active tmux window's name and uses it as a variable for my vim session. Is this possible? I looked through the tmux manual and didn't see anything.

Upvotes: 28

Views: 11895

Answers (4)

aghast
aghast

Reputation: 15310

The FORMATS section in the tmux man page contains a great deal of useful info. To wit:

  1. You can use "prebuild" format codes like #W
  2. There is a list of defined fields that can be printed individually, like window_name.
  3. There are "condition variables" that take the value 1 when true, and not-1 otherwise, like window_active.
  4. There are "conditional expressions" that expand to either of two values, depending on their target.

Putting that together, I came up with:

$ tmux list-windows -F "#{?window_active,#{window_name},}"
primary

$

Where "primary" is the name of my currently-active window (set moments before using tmux rename-window) and I have 2 other windows that are not active, and so presented as blank lines.

Considering the shell eats whitespace, you can probably do something like

ACTIVE_WINDOW=$(tmux list-windows -F "#{?window_active,#{window_name},}")

in a script.

Upvotes: 1

bilabila
bilabila

Reputation: 1163

First list all window names and active status, the active one will end with 1, then extract the name before it

 tmux lsw -F '#{window_name}#{window_active}'|sed -n 's|^\(.*\)1$|\1|p'

Upvotes: 2

Alex Kroll
Alex Kroll

Reputation: 481

SYNOPSIS tmux [-28lquvVC] [-c shell-command] [-f file] [-L socket-name] [-S socket-path] [command [flags]]

SKIP

command [flags] This specifies one of a set of commands used to control tmux, as described in the following sections. If no commands are specified, the new-session command is assumed.

You can find full list of tmux commands (two last arguments) in the manual, but now you interest is 'list-windows'.

tmux list-windows
0: zsh [156x40] [layout aebd,156x40,0,0,0] @0
1: mc [156x40] [layout aebe,156x40,0,0,1] @1 (active)

As you can see active window marked as '(active)'. This is what you were looking for?

Upvotes: 3

Chris Johnsen
Chris Johnsen

Reputation: 224949

You can use display-message -p to query the name of the active window (among other things):

tmux display-message -p '#W'

If you want to target a specific window, you can use -t:

tmux -t «target-window» display-message -p '#W'

See the man page for the various ways to specify a target window (search for “target-window” in the Commands section).

Upvotes: 36

Related Questions