3

If the path ~/dev/project1/node_modules/.bin/ionic exists, and my working directory is ~/dev/project1, I would like to be able to just type ionic and hit enter.

I could include all those subdirectories to PATH but I'm curious if there's a cleaner way. I'm looking to add some magic so my path always includes that subdirectory relative to whatever my current working directory is.

Bonus points if you can make it search all parent directories for that subdirectory and add all of them to the path.

5
  • I am not sure what the question is. If you put the absolute path of all the directories you want on PATH to your .bashrc or equivalent file, wouldn't it solve the problem? Commented Feb 26, 2015 at 18:47
  • 2
    This is a serious security risk to include relative paths in your PATH. Duplicate to stackoverflow.com/questions/11621639/… Commented Feb 26, 2015 at 18:54
  • 2
    faqs.org/faqs/unix-faq/faq/part2/section-13.html Commented Feb 26, 2015 at 18:56
  • 2
    . used to be in the path, but was removed for security reasons. However if you have to do it then but it at the end of the list, so that it can not override the default commands, such as ls. …:./sub_directory/.bin Commented Feb 26, 2015 at 19:44
  • @richard that seems to be the answer, care to make it one? Commented Feb 26, 2015 at 21:28

1 Answer 1

2

You can put relative paths in the search path. It's dangerous, because it could cause you to execute unexpected binaries when you're in a directory which isn't part of your project; don't do it on a multi-user machine.

PATH=…;node_modules/.bin/ionic;…

For more safety and flexibility, you can change the search path each time the current directory changes. In your .bashrc:

cd () { builtin cd "$@" && chpwd; }
pushd () { builtin pushd "$@" && chpwd; }
popd () { builtin popd "$@" && chpwd; }
chpwd () {
  if [[ $PATH = */node_modules/.bin/ionic ]]; then
    PATH=${PATH%:*}
  fi
  if [[ $PWD =~ ^"$HOME/dev/"[^/]* ]]; then
    project_root=${BASH_REMATCH[0]}
    PATH=$PATH:${project_root}/node_modules/.bin/inoic
  fi
}
chpwd
2
  • Thanks Gilles! That's some serious bash foo. For anyone that is mostly bash illiterate like me that second condition adds paths to $PATH if you're currently in ~/dev and a path like ~/dev/project/**/node_modules/.bin exists - it can be nested any number of directories. The first condition removes directories added by the second condition. Amazing! One note I removed /ionic so any executable in .bin will work. Commented Feb 27, 2015 at 16:28
  • One note on my previous comment. I use $PWD instead of $project_root, so paths like ~/dev/project/client/node_modules/.bin will work. Commented Feb 27, 2015 at 16:48

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.