This is a follow-up question to eval cat inside a function.
I'm using eval
to mimic import
functionality from other languages (such as JavaScript). This is something I wanted to do on my local machine for a while since I've built up an overwhelming collection of script files.
The reasoning is that I now have a very large number of individual functions in separate files, and I don't want to constantly read files with source
again and again every time I want to call the functionality.
It's mostly just for fun, but I don't want to shoot my foot off should I ever use it in a less casual context:
import_as() {
import_name="$1"
import_fnname="${2:-"$import_name"}"
if test -f "$1"; then
echo "File '$1' doesn't exist."
fi
case "$2" in
*[!-a-zA-Z0-9_]* ) echo "BAD";;
*) eval "$2"'() { '"$(< $1.sh)"'; }' ;;
esac
}
Here's an example of it in use:
add.sh
#!/bin/sh
echo "$(($1 + $2))"
sub.sh
#!/bin/sh
echo "$(($1 - $2))"
example_import.sh
import_as "add" "math_add"
import_as "sub"
math_add 2 5 # Returns "7"
math_subtract 5 1 # Returns "4"
My question is whether or not this use case of eval
is vulnerable to exploits after the checks I've performed, or if there is something exploitable in this script?
PS: I understand eval
is considered evil, and I don't want to hear that as an answer. I want specific reasoning for this use case if you believe that in this use case of eval
there could be exploits.