Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

source all files in a directory from .bash_profile

People also ask

How do I get a list of files in a directory in Bash?

Use the ls Command to List Directories in Bash. We use the ls command to list items in the current directory in Bash.

Can you source in a bash script?

The source Command The built-in bash source command reads and executes the content of a file. If the sourced file is a bash script, the overall effect comes down to running it. We may use this command either in a terminal or inside a bash script.


Wouldn't

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

be sufficient?

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


Oneliner (only for bash/zsh):

source <(cat *)

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


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

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.