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.
Linux recursive directory listing using ls -R command. The -R option passed to the ls command to list subdirectories recursively.
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.
Show activity on this post. Not directly, no. Entries in $PATH are not recursive.
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.
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.
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 CLASSPATH
s.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With