TMUX setting environment variables for sessions

后端 未结 4 1805
故里飘歌
故里飘歌 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条回答
  •  感动是毒
    2021-02-04 00:38

    Example

    In my case I'm starting a tmux session per project within a bash script and I needed to activate a relevant virtual environment for that session, including any newly opened tabs. To do so, I added the following virtual environment activation code to the ~/.bashrc:

    if [ -n "$VIRTUAL_ENV" ]; then
        source $VIRTUAL_ENV/bin/activate;
    fi
    

    However if I need to set foo environment for Session_1 and bar environment for Session_2, the VIRTUAL_ENV variable is globally set to bar after creating Session_2, so any newly opened tabs in Session_1 erroneously ends up in bar environment.

    Solution

    original HOWTO (commit).

    1. Add the following in your ~/.profile (or ~/.bashrc):
    # For Tmux VirtualEnv support
    tmux_get_var(){
        local key=$1
        [[ -n "$TMUX" ]] && tmux showenv | awk -F= -v key="$key" '$1==key {print $2}'
    }
    
    # activate the virtual environment if it is declared
    venv=$(tmux_get_var "VIRTUAL_ENV")
    if [ -n "$venv" ]; then
        source $venv/bin/activate;
    fi
    
    1. Set the VIRTUAL_ENV variable for the target session:
    tmux setenv -t ${SESSION_NAME} 'VIRTUAL_ENV' /path/to/virtualenv/
    

提交回复
热议问题