在 PATH 环境变量中包含命令

Include command inside PATH environment variable

是否可以在 PATH 中包含一个命令,即每当读取 PATH 时 运行?

用例: 我想将 npm bin 的输出添加到我的路径中,这样我就可以访问本地 npm 包二进制文件而无需键入 $(npm bin)/grunt。如果我 cd 到另一个节点项目,我希望我的路径更新为指向 npm bin.

的新输出

最好的办法是在每次目录更改时更新路径。按照这些思路应该可以做到:

 # 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

另一种方法是定义一堆函数,例如

 function grunt() { $(npm bin)/grunt $@ }