Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set environmental variables in a particular directory

This is a .bashrc question. I would like to set "export FOO=bar" for .bashrc in a particular directory like .rvmrc.

I tried below.

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

But RAILS_ENV shall be set nothing in this case.

If I set onto .rvmrc instead of .bashrc, it pass! But it is better way to set onto .bashrc because I do not need to install rvm environment.

Any solutions?

like image 481
diveintohacking Avatar asked Jan 22 '13 15:01

diveintohacking


People also ask

How do I set environment variable in CMD?

To set an environment variable, use the command " export varname=value ", which sets the variable and exports it to the global environment (available to other processes). Enclosed the value with double quotes if it contains spaces. To set a local variable, use the command " varname =value " (or " set varname =value ").


2 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's written actually ) the command above checks the $PWD variable ( which holds the current working directory of your shell ) against "/foo/bar" if it matches it exports your variable if it doesn't then the variable is unset.

EG

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$ 
like image 57
peteches Avatar answered Nov 09 '22 22:11

peteches


If you don't mind to use a workaround, add this 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

Everytime you move to a certain folder this will set your env variable or whatever you want

like image 27
Davide Berra Avatar answered Nov 09 '22 22:11

Davide Berra