Search code examples
bashshellevalcat

eval cat inside a function


I've been trying to evaulate an expression inside a function as follows:

eval "fn() { $(cat fn.sh); }"

Where fn.sh contains the following:

#!/bin/sh
echo "You provided $1."

So that when I call:

fn "a phrase"`

it prints "You provided a phrase.". However I cannot get it to work.

What's particularly frustrating is that:

eval "$(cat fn.sh)"

works perfectly! What am I missing here?

What I've tried:

eval "fn() { \"\$(cat fn.sh)\"; }"
fn
# bash: #!/bin/sh
# echo "You provided $1."
# return 1: No such file or directory

eval "fn() { \$(cat fn.sh); }"
fn
# bash: #!/bin/sh: No such file or directory

and myriad other combinations, most of which at this point is guess work.


Solution

  • Found the answer:

    eval "fn() { eval \"\$(cat "fn.sh")\"; }"
    

    Mandatory reference that explains to the best degree I understand the security risks of using eval.