Moe
Moe

Reputation: 1356

directory specific PATH variable

I want to change my PATH variable depending on the current directory.

For a project I'm using a set of scripts that I would like to run without specifying the full path to the script. Normally I would do that by adding the "Scripts" directory to the PATH variable.

The thing is, for my other projects I don't want to have these Scripts in my PATH. Is there a way to change the PATH variable according to the current directory? If so I'd be happy to learn how.

Upvotes: 4

Views: 1416

Answers (3)

rlduffy
rlduffy

Reputation: 618

From direnv.org

"The direnv project aims to allow path-dependent environment variables in your shell. It has many uses but mine it to have project-specific settings so as to not clutter my ~/.profile. I’m using it to specify ruby version, set AWS or SSH keys, …"

Upvotes: 4

Michał Kosmulski
Michał Kosmulski

Reputation: 10020

If you need the modified paths to work only for your convenience when working from the console, you could override cd:

function cd() {
    builtin cd "$@"
    case $(pwd) in
        */project1*) export PATH=somepath1;;
        */project2*) export PATH=somepath2;;
        ...
    esac
}
export -f cd

This will of course only work if you change the directory using shell's cd command, not if an application changes it using C API for example. This code is also a bit tricky, as you have to list a number of PATH values and be sure to handle reasonably the case for "standard" directories (those outside from your projects) where you probably want to reset PATH to the original value. Also, you may run into interactions with users or scripts manually modifying their PATH values. The values you set should include those, but you will need to store PATH in a temporary variable, like ORIG_PATH, before overriding cd.

Point is: what you ask for is possible (as shown above), but it may cause confusion and require some work. Config scripts sourced when you switch between projects that jcollado suggested are the standard and a much cleaner solution.

Upvotes: 0

jcollado
jcollado

Reputation: 40424

I'd say that the usual way to handle project dependent configuration is to have a configuration script for every project and source it when working on that project. Additionally, the configuration script used may change the prompt so that you become aware of what's the active project for a given shell just looking at it.

Upvotes: 2

Related Questions