i don't know how to explain a question... but here is what I mean
function make_dynamic_functions
{
echo "function fast_multiregex_check"
echo "{"
for i in 123410[0-9]* 123430[0-9]* 1235[89][0-9]{0,5} 1237[89][0-9]{8,} 1235551[0-9]*
do
echo "if [[ \$1 =~ ^$i\$ ]]; then"
echo "echo $i"
echo "exit"
echo "fi"
done
echo "}"
eval all-output-from-previous-echos
}
This seems to work:
fntext=$(cat <<EOF
function myfunc () {
echo hello world
}
EOF
)
And then:
$ eval "$fntext"
$ myfunc
hello world
Although given your example, you could just dump all your output to a temporary file and then source it in with the . operator:
function make_dynamic_functions
{
(
echo "function fast_multiregex_check"
echo "{"
for i in 123410[0-9]* 123430[0-9]* 1235[89][0-9]{0,5} 1237[89][0-9]{8,} 1235551[0-9]*
do
echo "if [[ \$1 =~ ^$i\$ ]]; then"
echo "echo $i"
echo "exit"
echo "fi"
done
echo "}"
) > tmpfile
. tmpfile
}
You can build a string with the text of the function, then eval the string:
function make_dynamic_functions
{
func="function fast_multiregex_check"
func="$func {"
for i in 123410[0-9]* 123430[0-9]* 1235[89][0-9]{0,5} 1237[89][0-9]{8,} 1235551[0-9]*
do
func="$func; if [[ \$1 =~ ^$i\$ ]]; then"
func="$func echo $i;"
func="$func exit;"
func="$func fi;"
done
func="$func }"
eval "$func"
}
The alternative mechanism is to capture the output of the various echo commands with func=$( ...echos... ) and then eval that string. The trick with building up the string is to ensure that the semi-colons are in all the right places - it is probably easier with echo commands, but you have to remember to quote the value passed to eval to preserve the internal newlines.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With