在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包含if , for或其他语句,则command not found
我们可以使用eval ,但不能拿出一个参数
如何find所有包含来源的目录?
如何在ImageMagick中使用带标题的stdin
Grep正则Expression式Mac地址
安装composer时出错 – curl:(23)Failed writing body(0!= 16133)
“无法统计远程文件:没有这样的文件或目录”:在shell脚本中使用FTP从* nix到Win
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
Bash脚本正则Expression式
重命名所有'。' 除了扩展名以外的文件名中加上'_'
以更好的方式分配variables值
shell脚本如果语句麻烦
Uniqing基于字段子集的分隔文件
整个命令行存储在一个变量是不安全的,会有很多问题。
改用功能:
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节目那样解决问题。
总结以上是内存溢出为你收集整理的如何从variables执行一个bash命令全部内容,希望文章能够帮你解决如何从variables执行一个bash命令所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)