How to use env variable in a tmux bind-key map?

I want my bind-key command to make use of a variable.

Here is my .tmux.conf file:

# .tmux.conf bind-key r rename-session $MY_VARIABLE 

How can I set MY_VARIABLE on a session-by-session basis?

Things I have tried that did not work:

  • Run export MY_VARIABLE=my_value in bash before pressing C-b r.
  • Run tmux setenv MY_VARIABLE my_value in bash before pressing C-b r.

(C-b is my prefix in tmux)

The following (based on this answer) DOES WORK:

Add a line to to .tmux.conf, like this:

# .tmux.conf MY_VARIABLE=my_value bind-key r rename-session $MY_VARIABLE 

Running C-b r the successfully renames the session. But this is less than ideal, because MY_VARIABLE=my_value is hard-coded into the .tmux.conf file; I want a way to change MY_VARIABLE on an ad-hoc basis.

1 Answer

Typically, the way round this is to go through the shell again, eg:

bind-key r run-shell 'tmux rename-session "$MY_VARIABLE"' 

The single quotes stops the variable from being expanding whilst parsing the config file. If you then later say

tmux setenv MY_VARIABLE my_value 

it will set the session environment. When you then type prefix-r the shell forked by run-shell will inherit these session variables, and the shell will be able to replace the variable by the current value for the session.

0

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like