How to set and use variable in tmux.conf depending on whether an environment variable is set

The way tmux runs the config is by parsing the config file into a set of commands, and then executing them (there is a command queue, so the config file is parsed and appended to the queue and then executed from the queue). So there are distinct parse and execution steps.

The problem you are running into with attempt 1, is that the if-shell is run at execution time, but the $VALUE expansion happens at parse time. VALUE is not set when the set-environment command is parsed.

In attempt 2, #() is not processed inside %if so that won't work. However, you can use the variable directly in formats (if it is set). %if happens at parse time.

So you need to make sure assignment and expansion happen in the right order. You have a couple of choices.

You could make tmux expand the variable at command execution time rather than parse time. You can do this by wrapping the setenv inside run-shell, so something like:

   if-shell '[ -z "$FOO" ]' \
       'VALUE=bar' \
       'VALUE=baz'
   run 'tmux setenv -g RESULT $VALUE'

Or you could do the assignment at parse time like you tried in attempt 2, but you can't use #() - you need to use a format instead:

   %if #{==:#{FOO},}
   VALUE=bar
   %else
   VALUE=baz
   %endif
   setenv -g RESULT $VALUE

(Note that X=Y in the config file is equivalent to setenv -g X=Y except it happens when parsing rather than executing - both set the global environment. So you could get rid of VALUE and do either RESULT=bar or setenv -g RESULT bar inside the %if.)

Tags:

Tmux