source all files in a directory from .bash_profile

Viewed 44150

I need to allow several applications to append to a system variable ($PYTHONPATH in this case). I'm thinking of designating a directory where each app can add a module (e.g. .bash_profile_modulename). Tried something like this in ~/.bash_profile:

find /home/mike/ -name ".bash_profile_*" | while read FILE; do
source "$FILE"
done;

but it doesn't appear to work.

8 Answers

You can use this function to source all files (if any) in a directory:

source_files_in() {
    local dir="$1"

    if [[ -d "$dir" && -r "$dir" && -x "$dir" ]]; then
        for file in "$dir"/*; do
           [[ -f "$file" && -r "$file" ]] && . "$file"
        done
    fi
}

The extra file checks handle the corner case where the pattern does not match due to the directory being empty (which makes the loop variable expand to the pattern string itself).

str="$(find . -type f -name '*.sh' -print)"
arr=( $str )
for f in "${arr[@]}"; do
   [[ -f $f ]] && . $f --source-only || echo "$f not found"
done 

I tested this Script and I am using it. Just modifiy the . after find to point to your folder with your scripts and it will work.

Related