source all files in a directory from .bash_profile

本秂侑毒 提交于 2019-12-17 18:03:52

问题


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.


回答1:


Wouldn't

 for f in ~/.bash_profile_*; do source $f; done

be sufficient?

Edit: Extra layer of ls ~/.bash_* simplified to direct bash globbing.




回答2:


I agree with Dennis above; your solution should work (although the semicolon after "done" shouldn't be necessary). However, you can also use a for loop

for f in /path/to/dir*; do
   . $f
done

The command substitution of ls is not necessary, as in Dirk's answer. This is the mechanism used, for example, in /etc/bash_completion to source other bash completion scripts in /etc/bash_completion.d




回答3:


Oneliner (only for bash/zsh):

source <(cat *)



回答4:


aus man bash:

source filename [arguments]

ein source config/*

The first argument will be sourced and all other files in config/ will be arguments to the script it sources.




回答5:


for file in "$(find . -maxdepth 1 -name '*.sh' -print -quit)"; do source $file; done

This solution is the most postable I ever found, so far:

  • It does not give any error if there are no files matching
  • works with multiple shells including bash, zsh
  • cross platform (Linux, MacOS, ...)



回答6:


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 and I am using it. Just modifiy the . after find to point to your folder with your scripts and it will work.




回答7:


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).




回答8:


ok so what i ended up doing;

eval "$(find perf-tests/ -type f -iname "*.test" | while read af; do echo "source $af"; done)"

this will execute a source in the current shell and maintian all variables...




回答9:


I think you should just be able to do

source ~/.bash_profile_*



来源:https://stackoverflow.com/questions/1423352/source-all-files-in-a-directory-from-bash-profile

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!