Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
844 views
in Technique[技术] by (71.8m points)

bash - How to recursively add subdirectories to the PATH?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

At the end of your script, put the line:

PATH=${PATH}:$(find ~/code -type d | tr '
' ':' | 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 '
' ':' | 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 '
' ':' | 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...