Set environment variables in a specific directory

This is a .bashrc question. I would like to set "export FOO=bar"

for .bashrc in a specific directory eg .rvmrc

.

I tried below.

$ touch ~/foo/.bashrc
$ echo 'export RAILS_ENV=development' >> ~/foo/.bashrc
$ cd foo/
$ env|grep RAILS_ENV

      

But RAILS_ENV

in this case, nothing will be asked.

If I put on .rvmrc

instead of .bashrc it gets through! But it's better to install on .bashrc

because I don't need to install the rvm environment.

Any solutions?

+3


source to share


3 answers


in your bashrc set this:

PROMPT_COMMAND='[[ $PWD == "/foo/bar/" ]] && export FOO=BAR || unset FOO'

      

The contents of the PROMPT_COMMAND variable will be executed every time your prompt is rewritten (just before it is actually written), the above command checks the $ PWD variable (which contains your shell's current working directory) against "/ foo / bar" if it matches it, exports your variable, if it hasn't changed, the variable is not set.



E.G.

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$ 

      

+8


source


If you don't mind using a workaround add it to your .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

      



Every time you go to a specific folder, this sets your env variable or whatever you want.

+4


source


First, AFAIK, bash

it won't look for the file .bashrc

in any other directory other than your home - at least not by default.

Second, after writing new entries to .bashrc

, you must source .bashrc

save the file for the changes to take place.

+3


source







All Articles