Bash – Shell script with function and parameter as Variables

bashfunctionscripting

i got a shell script where the function name and its parameters is stored in variables. I don't know how to call it. I tried it with eval and without, but nothing works correctly.

example of my code:

VarFunction="Testfunc1"
VarName="Peter"
VarLastname="Lustig"
VarText="Is a really lucky guy!\n Maybe he knows some funny Stuff?"

eval ${VarFunction} "$VarName" "$VarLastname" "$VarText"


Testfunc1() {
     Name=$1
     LastName=$2
     Text=$3

     echo $Name 
     echo $Lastname
     echo $Text

}

When the function itself is not a variable, the script works fine.

Testfunc1 "$VarName" "$VarLastname" "$VarText"

But i want to call a function dynamicly.

How can i do that?

Thanks and greetings

Danloc

Best Answer

This is about where you put the function definition. If you declare the function before it's called, you can call it even by variable. Try this:

VarFunction="Testfunc1"
VarName="Peter"
VarLastname="Lustig"
VarText="Is a really lucky guy!\n Maybe he knows some funny Stuff?"
Testfunc1() {
     Name=$1
     LastName=$2
     Text=$3

     echo $Name 
     echo $Lastname
     echo $Text 
}
${VarFunction} "$VarName" "$VarLastname" "$VarText"
Related Question