Question

I'm trying to add a set of subdirectory's to my PATH in as simple a way as possible.

Currently the structure is:

main_project/
   subproject/bin/
   subproject2/bin/
   subproject with spaces/bin/

I'm currently using the simple bash-fu in my .bash_profile:

PATH="$PATH:$(echo /projects/main_project/*/bin | tr ' ' ':')"

The problem is the path with spaces comes out as:

subproject:with:spaces/bin/ in my $PATH

Was it helpful?

Solution

You should be using printf instead:

PATH="$PATH$(printf ":%s" /projects/main_project/*/bin)"

OTHER TIPS

A loop would be clearer:

for subproj in /projects/main_project/*/bin; do
    PATH+=":$subproj"
done

Another possibility (abusing IFS—but it's here for this kind of purposes too!):

scratch=( /projects/main_project/*/bin )
IFS=: read -r PATH <<< "$PATH:${scratch[*]}"

The stuff below is probably overkill and useless for your purpose!

If you want something more robust, that works as expected even if PATH is unset or null:

scratch=( /projects/main_project/*/bin )
IFS=: read -r PATH <<< "${PATH:+$PATH:}${scratch[*]}"

Finally you might (rightly!) think that it's not safe to use globs without any safety (i.e., without the shell option nullglob or failglob) set:

old_nullglob=$(shopt -p nullglob)
shopt -s nullglob
scratch=( /projects/main_project/*/bin )
((${#scratch})) && IFS=: read -r PATH <<< "${PATH:+$PATH:}${scratch[*]}"
$old_nullglob

Another thought, what if these are already in your PATH? I'll leave it as homework!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top