Bash – Defining bash function dynamically using eval

bashfunctionshell-script

I'm trying to define a bash function dynamically using following code:

delegate_function() { echo "output from delegate"; }
eval "parent_function() { echo $(delegate_function); }"

The intent is to have parent function dynamically dispatch to the delegate when executed. However due to the way eval works my function is being defined as follows:

kshitiz:/tmp$ type parent_function
parent_function is a function
parent_function () 
{ 
    echo output from delegate
}

How can I instead have the definition as:

 parent_function () 
 { 
     echo $(delegate_function);
 }

Is there a way to escape some part of the string from being evaluated by eval?

Best Answer

Escaping $ should be enough to make this work:

eval "parent_function() { echo \$(delegate_function); }"