TMUX setting environment variables for sessions

user1223028 picture user1223028 · Dec 20, 2013 · Viewed 26.3k times · Source

I work in a situation where I have multiple projects and within each are many scripts that make use of environment variables set to values specific to that project.

What i'd like to do is use a separate tmux session for each project and set the variables so that they are set for all windows in that session.

I tried to use the set-environment option which works using the -g option but then sets the variable for all sessions connected to that server.

Without the -g option I see its set when using show-environment but can't access the variable in the shell.

Has anyone come up with a way of fixing this?

Using tmux 1.8 and tcsh

Answer

RobotNerd picture RobotNerd · Mar 21, 2018

I figured out a way to do this. I'm using tmux 2.5.

Background

In the tmux man page, it states that there are two groups of environment variables: global and per-session. When you create a new tmux session, it will merge the two groups together and that becomes the set of environment variables available within the session. If the environment variables get added to the global group, it appears that they get shared between all open sessions. You want to add them to the per-session group.

Do this

Step 1: Create a tmux session.

tmux new-session -s one

Step 2: Add an environment variable to the per-session group.

tmux setenv FOO foo-one

This adds the environment variable to per-session set of environment variables. If you type tmux showenv, you'll see it in the output. However, it isn't in the environment of the current session. Typing echo $FOO won't give you anything. There's probably a better way to do this, but I found it easiest to just export it manually:

export FOO='foo-one'

Step 3: Create new windows/panes

Now, every time you create a new window or pane in the current session, tmux will grab the FOO environment variable from the per-session group.

Automating it

I use bash scripts to automatically create tmux sessions that make use of these environment variables. Here's an example of how I might automate the above:

#!/bin/bash
BAR='foo-one'
tmux new-session -s one \; \
  setenv FOO $BAR \; \
  send-keys -t 0 "export FOO="$BAR C-m \; \
  split-window -v \; \
  send-keys -t 0 'echo $FOO' C-m \; \
  send-keys -t 1 'echo $FOO' C-m