eval cat inside a function

北慕城南 提交于 2019-12-13 02:59:25

问题


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.



来源:https://stackoverflow.com/questions/52369629/eval-cat-inside-a-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!