我想执行一个由变量(cmd
在此示例中为变量)给出的命令:
cmd="echo 'First argument'"
$cmd
预期结果将是:
First argument
但是...实际结果是:
'First argument'
什么?我不明白为什么我可以在输出中看到单引号。毕竟,如果将直接发出命令(=变量$ cmd的内容),则不会在输出中引起引号,它的行为如预期:
$ echo 'First argument'
First argument
为了说明我在现实生活中想要实现的目标:在我的部署脚本中,有一个这样的代码块(经过简化,但您明白了):
#!/bin/bash
function execute {
cmd=$1
echo "Executing $cmd ..."
# execute the command:
$cmd
}
VERSION=1.0.2
execute "git tag -a 'release-$VERSION'"
现在,Git将创建一个包含单引号的标签:
git tag
'1.0.2'
这不是我想要的...
该怎么办?
(bash版本:GNU bash 3.1.0)
(我在这里发现了一个非常相似的问题,但答案不适用于我的问题)
cmd="echo 'First argument'"
$cmd
发生单词拆分时会发生什么,实际的结果命令是:
echo "'First" "argument'"
用单引号引起来的双语法分析将永远不会发生。
另外,最好使用数组:
#!/bin/bash
function execute {
cmd=("$@") ## $@ is already similar to an array and storing it to another is just optional.
echo "Executing ${cmd[*]} ..."
# execute the command:
"${cmd[@]}"
}
VERSION=1.0.2
execute git tag -a "release-$VERSION"
对于eval
在那种情况一个艰难的选择。您不仅会获得意外的解析结果,而且还会意外地运行危险的命令。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句