Gilbert Gillemore
Gilbert Gillemore

Reputation: 31

How to create function with eval

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
    }

Upvotes: 3

Views: 831

Answers (2)

Jonathan Leffler
Jonathan Leffler

Reputation: 755044

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.

Upvotes: 2

Codemonk
Codemonk

Reputation: 441

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
}

Upvotes: 4

Related Questions