在特定目录中设置环境变量

gip*_*any 5 linux variables bash

这是一个.bashrc问题.我想"export FOO=bar"在特定的目录中设置.bashrc .rvmrc.

我在下面试过.

$ touch ~/foo/.bashrc
$ echo 'export RAILS_ENV=development' >> ~/foo/.bashrc
$ cd foo/
$ env|grep RAILS_ENV
Run Code Online (Sandbox Code Playgroud)

RAILS_ENV在这种情况下不得设置任何东西.

如果我设置.rvmrc而不是.bashrc,它会通过!但这是更好的设置方式,.bashrc因为我不需要安装rvm环境.

有解决方案吗

pet*_*hes 10

在你的bashrc中设置:

PROMPT_COMMAND='[[ $PWD == "/foo/bar/" ]] && export FOO=BAR || unset FOO'
Run Code Online (Sandbox Code Playgroud)

PROMPT_COMMAND变量的内容将在每次重写提示时执行(在实际写入之前)上面的命令检查$ PWD变量(它保存shell的当前工作目录)对"/ foo/bar"如果它匹配它导出你的变量,如果没有,那么变量是未设置的.

例如

peteches@yog-sothoth$ PROMPT_COMMAND='[[ $PWD == "/home/peteches/test" ]] && export FOO=BAR || unset FOO'
peteches@yog-sothoth$ pwd
/home/peteches
peteches@yog-sothoth$ cd test
peteches@yog-sothoth$ pwd
/home/peteches/test
peteches@yog-sothoth$ env | grep FOO
6:FOO=BAR
73:PROMPT_COMMAND=[[ $PWD == "/home/peteches/test" ]] && export FOO=BAR || unset FOO
peteches@yog-sothoth$ cd ../
peteches@yog-sothoth$ pwd
/home/peteches
peteches@yog-sothoth$ env | grep FOO
72:PROMPT_COMMAND=[[ $PWD == "/home/peteches/test" ]] && export FOO=BAR || unset FOO
peteches@yog-sothoth$ 
Run Code Online (Sandbox Code Playgroud)


Dav*_*rra 5

如果您不介意使用变通方法,请将其添加到您的 .bash_profile

mycd()
{
    cd $1
    if [ "$(pwd)" == "/your/folder/that/needs/env" ]; then
        export RAILS_ENV=development
    else
        export RAILS_ENV=
    fi;
}
alias cd=mycd
Run Code Online (Sandbox Code Playgroud)

每次移动到某个文件夹时,这将设置您的env变量或任何您想要的


dcr*_*n22 5

查看direnv

direnv是你的 shell 的扩展。它通过一项新功能增强了现有的 shell,该功能可以根据当前目录加载和卸载环境变量。

基本上检查.envrc位于当前或父目录中的文件,并相应地调整环境变量。