You could use eval
, but I dislike using eval
as a general rule. It's incredibly tricky to get all the quoting and escaping right, which means it's very, very easy to do unsafe things. Scripts that use eval
are highly prone to input injection attacks where attackers feed in bad input or put weirdly named files on the filesystem and trick scripts into running arbitrary commands.
I would write out all of the function declarations, minimizing boilerplate with a crafty helper function that looks up the name of the caller. Bash provides an array called FUNCNAME
that names all of the functions in the call stack. ${FUNCNAME[0]}
is the name of the current function and ${FUNCNAME[1]}
is the calling function.
helper() {
. mydir/"${FUNCNAME[1]}"
}
a() { helper; }
b() { helper; }
c() { helper; }
If the names are dynamic, you could cautiously venture to use eval
:
cd mydir/
for file in *; do
[[ $file =~ ^[a-z]+$ ]] || continue
eval "$file() { helper; }"
done
I've put a validation check in there to skip over any funky file names. We don't want to be led astray by file names containing ;
and ||
and the like.