How to capture session name into tmux variable?

4

1

I want to execute an external command based on the value of my session name. I know that the :display-message '#S' will give me the session name, but I want to have that name automatically sent to my external command.

I've tried :run-shell "my-command #S", but it does not work, as "#S" is not substituted.

Is there anything like :MY_VAR=$(display-message -p "#S") that I could use?

src

Posted 2012-08-07T18:03:48.437

Reputation: 331

Has there been any progress on this? tmux 1.9 still does not expand #(/bin/echo "#S"). Instead it passes "#S", not the acutal session name – Michael Krupp – 2015-05-06T18:50:11.437

Answers

1

Since you can run almost all tmux commands directly from a shell (not just from a tmux : prompt), you can do this:

:run-shell "my-command \"$(tmux display -p '#S')\""

Of course this can also be done from a binding:

:bind C run-shell "my-command \"$(tmux display -p '#S')\""

Chris Johnsen

Posted 2012-08-07T18:03:48.437

Reputation: 31 786

But if I have two different sessions open, it will print the name of the session that's currently in focus, not necessarily the session that spawned run-shell... – src – 2012-08-09T18:37:16.107

Right, the environment created for the commands started by run-shell is the “global” environment, so “the current session” will always refer to the most recently active session (because the last component of the value of the TMUX environment variable is -1 instead of an (internal) session index). If you want to run a command inside the context of a session, then maybe you should use a (transient) detached window to run your command: new-window -d 'my-command "$(tmux display -p "#S")"' (or write my-command to do the tmux display -p '#S' part itself instead of its parent shell doing it). – Chris Johnsen – 2012-08-10T03:52:09.423

1

If you are running tmux 1.8 (you can check with tmux -V), you can simply use :run-shell "my-command '#S'". This doesn't work in 1.6, though.

Luca Invernizzi

Posted 2012-08-07T18:03:48.437

Reputation: 156

0

You could use sed + xargs to pass the result as a parameter to your desired command, eg:

tmux bind-key "C" run-shell "tmux display-message -p '#{S}' | sed 's/.*/\"&\"/' | xargs my_command"

Javier López

Posted 2012-08-07T18:03:48.437

Reputation: 133