Directory based environment variable scope - how to implement?

12,147

Solution 1

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

Solution 2

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.

Solution 3

I've written another implementation of this, which is somewhat similar to ondir. I didn't actually know about ondir when I started working on it. There are some key differences that may be useful, however.

  • smartcd is written entirely in shell, and is fully compatible with bash and zsh, even the more esoteric options

  • smartcd will run scripts all the way down and up the directory hierarchy down to their common ancestor, not just for the two directories you're entering and leaving. This means you can have a ~/foo script that will execute whether you "cd ~/foo" or "cd ~/foo/bar"

  • it has "variable stashing" which is a more automatic way of dealing with your environment variables, whereas ondir requires you to explicitly and manually remove and/or reset your variables

  • smartcd can work with "autocd" turned on by hooking your prompt command (PROMPT_COMMAND in bash, precmd in zsh)

You can find smartcd at https://github.com/cxreg/smartcd

Solution 4

This is not something that is directly supported with the built-in features of bash or any other common shell. However, you can create your own "cd" command that will do whatever you want. For example, you could alias cd to do the cd and then run a special script (eg: ~/bin/oncd). That script could look up the new directory in a database and run some commands, or see if there's a special file (eg: .env) in the directory and load it, etc.

Share:
12,147
Igor Gatis
Author by

Igor Gatis

Updated on June 02, 2022

Comments

  • Igor Gatis
    Igor Gatis about 2 years

    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?