zsh运行存储在变量中的命令?

时间:2012-12-02 00:21:17

标签: shell scripting zsh

在shell脚本中(在.zshrc中)我试图执行一个命令,该命令作为字符串存储在另一个变量中。网络上的各种消息来源说这是可能的,但我没有得到我期望的行为。也许这是命令开头的~,或者可能是sudo的使用,我不确定。有任何想法吗?感谢

function update_install()
{
    # builds up a command as a string...
    local install_cmd="$(make_install_command $@)"
    # At this point the command as a string looks like: "sudo ~some_server/bin/do_install arg1 arg2"
    print "----------------------------------------------------------------------------"
    print "Will update install"
    print "With command: ${install_cmd}"
    print "----------------------------------------------------------------------------"
    echo "trying backticks"
    `${install_cmd}`
    echo "Trying \$()"
    $(${install_cmd})
    echo "Trying \$="
    $=install_cmd
}

输出:

Will update install
With command: sudo ~some_server/bin/do_install arg1 arg2

trying backticks
update_install:9: no such file or directory: sudo ~some_server/bin/do_install arg1 arg2
Trying $()
update_install:11: no such file or directory: sudo ~some_server/bin/do_install arg1 arg2
Trying $=
sudo ~some_server/bin/do_install arg1 arg2: command not found

2 个答案:

答案 0 :(得分:17)

使用eval

eval ${install_cmd}

答案 1 :(得分:10)

正如§3.1 "Why does $var where var="foo bar" not do what I expect?" of the Z-Shell FAQ中所述,您可以使用shwordsplit shell选项告诉zsh您希望它按空格分割变量并将其视为多个单词。同一页面还讨论了您可能需要考虑的替代方案。