Bash – How to get ~/.bashrc to execute all scripts in the ~/Shell directory using a loop

bashrcforshell-script

I have shell scripts in my ~/Shell directory that I want to be run whenever Bash is started up as my usual user account. So what I have done is added the following to ~/.bashrc:

for i in `find ~/Shell/ -name "*.sh"`
do
    sh $i
done

but, for whatever reason the functions contained in files with the file extension .sh in my ~/Shell directory are not automatically loaded. For example, I have a function called abash in my ~/Shell/bash.sh file and running abash from a new user terminal gave an error stating that the command was not found.

I know I can just manually list all the files in my ~/Shell directory with a dot before them to get them executed at Bash startup time. For example, I used to have this in my ~/.bashrc file:

. ~/Shell/bash.sh
. ~/Shell/cd.sh
. ~/Shell/emerge.sh
...

and it worked fine, but I would rather a for loop to do this, as it would mean if I add any new shell scripts to ~/Shell I do not have to worry about adding them to ~/.bashrc.

I have also now tried:

for i in `find -name "~/Shell/*.sh"`
do
        sh $i
done

and:

for i in "~/Shell/*.sh"
do
        sh $i
done

and:

for i in `find -name '~/Shell/*.sh'`
do
        sh $i
done

with no success.

Best Answer

Put this in your .bashrc:

for rc in ~/Shell/*.sh
do
    . "$rc"
done

And you're off to the races!

A couple of notes:

The bash (and zsh etc) source command, while readable, is not universal and does not exist in dash, the most posixly correct shell I know. As it stands, this same code can be used to load code into almost any bourne-shell derivative.

The traditional naming convention for files to be directly sourced into the shell is to use a suffix of rc or .rc (as in .bashrc). rc stands for "run commands". The .sh extension is usually used for executable script programs. (These are only conventions -- not rules.)

Related Question