Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to recursively add subdirectories to the PATH?

Tags:

How do you do it? My directory code/, at work, is organized in folders and subfolders and subsubfolders, all of which (at least in theory) contain scripts or programs I want to run on a regular basis.

like image 301
user50264 Avatar asked Mar 18 '09 05:03

user50264


People also ask

How do you recursively list subdirectories?

Linux recursive directory listing using ls -R command. The -R option passed to the ls command to list subdirectories recursively.

Does path look in subdirectories?

Note that path search never applies to names containing a slash. And the shell only searches in exactly the directories listed in PATH (but empty entries are interpreted as references to . , the current directory). It won't look in sub-directories of its own volition; you would have to list the sub-directories in PATH.

Does path look recursively?

Show activity on this post. Not directly, no. Entries in $PATH are not recursive.

What is the path of subfolder?

Every directory except for the top-level root directory is a subdirectory of at least one directory. The list of parent directories of a directory or file is called its path.


2 Answers

At the end of your script, put the line:

PATH=${PATH}:$(find ~/code -type d | tr '\n' ':' | sed 's/:$//') 

This will append every directory in your ~/code tree to the current path. I don't like the idea myself, preferring to have only a couple of directories holding my own executables and explicitly listing them, but to each their own.

If you want to exclude all directories which are hidden, you basically need to strip out every line that has the sequence "/." (to ensure that you don't check subdirectories under hidden directories as well):

PATH=${PATH}:$(find ~/code -type d | sed '/\/\\./d' | tr '\n' ':' | sed 's/:$//') 

This will stop you from getting directories such as ~/code/level1/.hidden/level3/ (i.e., it stops searching within sub-trees as soon as it detects they're hidden). If you only want to keep the hidden directories out, but still allow non-hidden directories under them, use:

PATH=${PATH}:$(find ~/code -type d -name '[^\.]*' | tr '\n' ':' | sed 's/:$//') 

This would allow ~/code/level1/.hidden2/level3/ but disallow ~/code/level1/.hidden2/.hidden3/ since -name only checks the base name of the file, not the full path name.

like image 75
paxdiablo Avatar answered Oct 04 '22 07:10

paxdiablo


The following Does The Right Thing, including trimming hidden directories and their children and properly handling names with newlines or other whitespace:

export PATH="${PATH}$(find ~/code -name '.*' -prune -o -type d -printf ':%p')" 

I use a similar trick for automatically setting CLASSPATHs.

like image 25
Charles Duffy Avatar answered Oct 04 '22 07:10

Charles Duffy