Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Directory based environment variable scope - how to implement?

I have a set of tools which I need to pass parameters depending on the project I'm working on. I'd like to be able to automatically set a couple of environment variables based on the current directory. So when I switched between directories, my commonly used env vars would also change. Example:

Let's current directory is foo, thus if I do:

~/foo$ ./myscript --var1=$VAR1 

VAR1 would have some foo based value.

Then, let's say I switched to bar directory. If I do:

~/bar$ ./myscript --var1=$VAR1 

VAR1 should now have some bar based value.

Is that possible? How?

like image 326
Igor Gatis Avatar asked May 01 '11 13:05

Igor Gatis


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 ").

How do you set an environment variable in Python?

Environ and set default:With the environ dictionary variable value of the environment variable can be set by passing the key in the dictionary and assigning the value to it. With setdefault a default value can be assigned to the environment variable. Bypassing the key and the default value in the setdefault method.


2 Answers

There is direnv which helps you do this stuff much easily and in an elegant way. Just define a .envrc file in your project directory with all the env variables needed and it will source it once you cd into that folder.

like image 76
sreenivas Avatar answered Oct 14 '22 15:10

sreenivas


the ondir program lets you specify actions to run when you enter and leave directories in a terminal

like image 21
Dan D. Avatar answered Oct 14 '22 14:10

Dan D.