Over time i have developed a library of useful (ksh) functions which i use in most of my scripts. I use the ksh's FPATH variable to locate all these functions and use a standard environment-setting-function to always have the same environment in all my scripts.
Here is how i begin scripts:
#!/bin/ksh
# foo.ksh
# main()
if [ -z "$DEVELOP" ] ; then # set environment
. /usr/local/lib/ksh/f_env
else
. ~/lib/f_env
fi
# ... rest of code ....
$DEVELOP is a variable i set if i want to use a local copy of the function library for testing purposes. "/usr/local/lib/ksh/f_env" looks like this:
if [ -z "$NEVER_USE_THIS_VAR" ] ; then # recursion protection
# .... some more settings ...
if [ -z "$DEVELOP" ] ; then
typeset -x FPATH="/usr/local/lib/ksh" # set fnc path for fnc lib
FPATH="$FPATH:/usr/local/bin"
FPATH="$FPATH:/usr/local/sbin"
else
typeset -x FPATH=~/lib # for lib development
fi
# ...
typeset -x NEVER_USE_THIS_VAR="KILROY_WAS_HERE"
fi
This mechanism is quite handy because many functions in the library depend on other functions in the same library and this way all these depencies are solved automatically.
I would like to make this library compatible with the bash shell (ideally i would be able to use these functions from ksh and bash equally), but bash lacks the FPATH mechanism. I came up with the following solution, but obviously it is quite unsatisfactory and i wonder if there is a better way to achieve my goal:
(within f_env(), after setting the FPATH variable: )
# simulate FPATH for bash
if [ -n "$BASH_VERSION" ] ; then
IFS=:
for fFPathDir in $FPATH ; do
for fFFile in $fFPathDir/* ; do
if [ $( \
sed -n '/^$/d;/^#/!{p;q}' $fFFile |\
grep -c '^\(function \)*[^ ][^ ]* ()' \
) -gt 0 ] ; then
echo $fFFile
. $fFFile
fi
done
done
fi
Basically i circle through FPATH, look into every file and if the first non-comment-line begins with "function <some-name> ()" (this is the sed-grep-line) i parse it into the environment. This looks quite clumsy, unreliable and downright ugly, but with my limited knowledge of bash i was not able to find a better solution. Your suggestions are welcome.
bakunin