Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create function with eval

Tags:

function

bash

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
    }
like image 717
Gilbert Gillemore Avatar asked Aug 18 '26 21:08

Gilbert Gillemore


2 Answers

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
}
like image 111
Codemonk Avatar answered Aug 24 '26 13:08

Codemonk


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.

like image 21
Jonathan Leffler Avatar answered Aug 24 '26 14:08

Jonathan Leffler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!