Is there a way on *nix machines, to change the value of an environment variable depending on the current working directory?

I am working on an NPM/Node.js module.

Basically what I want to do, is change the path to an executable depending on the $PWD.

Here is a project root


the executable is in


when I am "within" /home/user/project, aka in any descendant of that path, then I want the value for the env variable to be the path to x

I have a script that can find x given the current path, but what I need is a way to run that script, every time the user changes directories.

This might slow down the machine a lot though, this type of hook. Is this type of hook possible? Is there a better/different solution?

I think this question is similar: https://superuser.com/questions/914087/can-i-change-my-path-dynamically-based-on-my-cwd

marked as duplicate by Jeff Schaller, Satō Katsura, dhag, countermode, thrig Feb 21 '17 at 22:38

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 1
    With ZSH you setup a chpwd hook function that runs whatever code you want. Yes, this can be slow especially if you cd into a wedged NFS directory. – thrig Feb 21 '17 at 20:47
  • yeah, thanks I need to support bash only at this point, this is for a lib, and not everyone has ZSH tmk – Alexander Mills Feb 21 '17 at 20:49
  • 1
    A cd wrapper function goes a long way towards this; there are similar Q's on the site. – Jeff Schaller Feb 21 '17 at 21:22
  • thanks Jeff - any link would be helpful if you think there is a standout discussion on this, not sure where to begin except the link I posted in the question. – Alexander Mills Feb 21 '17 at 21:30