如何从variables执行一个bash命令

在Linux Bash中,我们可以使用()从variables中执行简单的命令,并带参数。 例如:

 bash-3.2$ greet="echo hello $1" bash-3.2$ ($greet world) hello world 

但是如果我们引入其他控制语句就像

 bash-3.2$ greet="if [ 1 == 1 ]; then echo hello $1; fi" bash-3.2$ ($greet world) bash: if: command not found 

如果variables包含iffor或其他语句,则command not found

我们可以使用eval ,但不能拿出一个参数

 bash-3.2$ eval $greet hello bash-3.2$ eval $greet world bash: syntax error near unexpected token `world' 

如何用参数执行greet ? 希望它与以下工作

 bash-3.2$ greet="if [ 1 == 1 ]; then echo hello $1; fi" bash-3.2$ ($greet world) bash-3.2$ hello world 

整个命令行存储在一个变量是不安全的,会有很多问题。

改用功能:

 greet() { if [ 1 == 1 ]; then echo hello $1; fi; } 

然后将其称为:

 greet world 

哪个会输出:

 hello world 

更新:(根据下面的评论)

有了eval的已知风险,你可以这样做:

 greet='if [ 1 == 1 ]; then echo hello $1; fi' (set -- word && eval "$greet") 

这将输出:

 hello word 

if不是一个命令,它是一个关键字。 除非使用eval否则不能将其存储在字符串变量中。 这是因为关键字解析发生在变量扩展之前。

但是,你仍然可以像anubhava节目那样解决问题。