~ kballard
/.bash_profile
Allows you to use a hierarchy of files in ~/Library/init/bash (yes I use OS X) for your bash initialization. This allows me to do things like use one file for aliases, another for env vars, etc. It also allows me to have stuff in ~/Library/init/bash/shared and stuff in ~/Library/init/bash/local, and I can sync the shared dir between my machines.
# ~/.bash_profile
declare -a loaded_files
declare -a indexed_files
index () {
local file=$1
if [[ -f "$file" && -r "$file" ]]; then
indexed_files[${#indexed_files[@]}]=$file
else
echo 'index: file `'"$file"\'' does not exist or is not readable' >&2
fi
}
require () {
local file=$1
local fullpath=
for idx in "${indexed_files[@]}"; do
if [[ $idx = "$file" || "`basename "$idx"`" = "$file" ]]; then
fullpath="$idx"
fi
done
if [[ -z "$fullpath" ]]; then
echo 'require: file `'"$file"\'' not in the index' >&2
else
local found=no
for lf in "${loaded_files[@]}"; do
if [[ "$lf" = "$fullpath" ]]; then
found=yes
break
fi
done
if [[ "$found" = "no" ]]; then
loaded_files[${#foo[@]}]="$fullpath"
source "$fullpath"
fi
fi
}
nullglob=$(shopt -p nullglob)
shopt -s nullglob
for f in "$HOME"/Library/init/bash/{*/,}*.sh; do
index "$f"
done
eval "$nullglob"
for f in "${indexed_files[@]}"; do
require "$f"
done
unset -f require
unset -f index
unset -v loaded_files
unset -v indexed_files