Adobe
Adobe

Reputation: 13487

Bash: how to add subdirs to the PATH

In .bashrc I have added a dir where I put some scripts. Is that possible - to add all its subdir automatically - so that I would not have to add them one-by-one manually? (and wouldn't have to visit .bashrc every time I'll make a dir there)

Edit:

Using Laurent Legrand's solution, that's what I'm using now:

PATH=$PATH:/usr/local/share/NAMD_2.7_Linux-x86_64:/usr/local/share/jmol-12.0.31:/usr/local/share/NAMD_2.7_Linux-x86_64_orig:/usr/local/share/sage-4.6.2:/opt/mongoDB/bin

PATH=$PATH:$(find ~/Study/geek/scripts -type d -printf "%p:")

this adds the dir and its sub dirs.

Upvotes: 0

Views: 383

Answers (3)

Phlogisto
Phlogisto

Reputation: 1016

This is the best practice to add executables from /opt directory to the path:

for subdir in $(find /opt -maxdepth 1 -mindepth 1 -type d); do
  PATH="$subdir/bin:$PATH"
done
export $PATH

As all needed executables should be in /opt/*/bin, we are avoiding subdirs that are beyond /opt/* using -maxdepth 1 and the /opt dir itself with -mindepth 1. Also note that we added /bin to the end of each dir.

Same can be applied in your case with scripts. If you need more depth, just modify value of -maxdepth or remove it completely for infinite levels (same applies for -mindepth if main script path shoud be included). Just beware of ambiguity if same script name can be found in multiple subdirectory levels.

So, in your case you may just use:

for subdir in $(find $HOME/path/to/scripts -type d); do
  PATH="$subdir:$PATH"
done
export $PATH

Upvotes: 0

ohe
ohe

Reputation: 3683

in your .bashrc suppose that all your scripts are under ~/bin

maindir=~/bin
for subdir in `tree -dfi $maindir`
do
    PATH=$PATH:$subdir
done
export $PATH

can do the trick ...

Upvotes: 2

Laurent Legrand
Laurent Legrand

Reputation: 1144

Something like that should work

 PATH=$PATH:$(find your_dir -type d -printf "%p:")

Upvotes: 3

Related Questions