0

Is it possible to include a command inside the PATH, that's run whenever PATH is read?

Use case: I want to prepend the output of npm bin to my path so I have access to local npm package binaries without having to type $(npm bin)/grunt. If I cd to another node project, I'd want my path updated to point to the new output of npm bin.

az_
  • 1,493
  • 1
  • 16
  • 24
  • 1
    possible duplicate of [How to use package installed locally in node\_modules?](http://stackoverflow.com/questions/9679932/how-to-use-package-installed-locally-in-node-modules) – Leonid Beschastny Aug 27 '15 at 19:56
  • 1
    No (not that I know of). Huge security risk. You can have hooks (precmd hook is most appropriate here) though which could update your hard `PATH` variable before each prompt. – 4ae1e1 Aug 27 '15 at 22:56
  • Sorry, you should use chpwd hook. See Francisco's answer. – 4ae1e1 Aug 29 '15 at 03:03
  • @LeonidBeschastny This was supposed to be a general question, not specific to node or my use case. I only specified my use case as an example to where it might be helpful. – az_ Sep 15 '15 at 00:31

1 Answers1

0

Your best bet would be to update your path on every directory change. Something along these lines ought to do it:

 # define a "PRE_PATH"
 export PRE_PATH="/bin:/usr/bin" # <-- put your actual path here
 export PATH=$PRE_PATH

 function update_my_path() {
   local npm_path
   npm_path=`npm bin`
   if [[ -z $npm_path ]]; then
      PATH=${npm_path}:$PRE_PATH
      # do you need to rehash after redefining your $PATH? I don't know...
      rehash
   fi 
 }
 autoload -U add-zsh-hook
 add-zsh-hook chpwd update_my_path

an alternative would be to define a bunch of functions such as

 function grunt() { $(npm bin)/grunt $@ }
Francisco
  • 3,980
  • 1
  • 23
  • 27
  • A few issues: 1. usually `/usr/local/bin` overrides `/usr/bin` which in turn overrides `/bin`, not the other way round; 2. there shouldn't be spaces around assignment of `npm_path`, which is a syntactic error; 3. it is usually advised to use `$()` for command substitution; 4. `export` sets the export flag, so there's no point in exporting more than once; 5. whether to use `rehash`: to get updated completion, yes, because you want to update the `commands` array; otherwise no. – 4ae1e1 Aug 29 '15 at 03:01
  • Actually I might be wrong with my point 5. Maybe it's not necessary. – 4ae1e1 Aug 29 '15 at 03:05
  • @4ae1e1 that "sample"path at the top was really a sample path. I don't expect that bin:usr-bin:usr-local-bin to be taken seriously. I will change the answer to avoid confusion.... – Francisco Aug 30 '15 at 20:55