eval cat inside a function

2019-08-23 08:03发布

问题:

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.

回答1:

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.



回答2:

Just use source/. from inside the new function.

fn () {
  . fn.sh "$1"
}

If the function is used often enough where you think repeated disk I/O would be an issue, the file will almost certainly be in a disk cache when you call fn.