TMUX setting environment variables for sessions

后端 未结 4 1731
故里飘歌
故里飘歌 2021-02-04 00:07

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

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-04 00:31

    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
    

提交回复
热议问题