【问题标题】:Golang: Executing a command with it's argumentsGolang:使用它的参数执行命令
【发布时间】:2016-11-17 10:14:07
【问题描述】:

我正在尝试使用 go 执行命令。

executableCommand := strings.Split("git commit -m 'hello world'", " ")
executeCommand(executableCommand[0], executableCommand[1:]...)
cmd := exec.Command(command, args...)

但这是我得到的

error: pathspec 'world"' did not match any file(s) known to git.
exit status 1

这是因为-m 仅获得'hello 而不是'hello world',因为命令行是使用" " 拆分的。

有什么办法让它发挥作用吗?

【问题讨论】:

    标签: git go command-line command


    【解决方案1】:

    如果没有解释引号等的 shell 的帮助,你想要的实际上是很难实现的。所以你可以使用 shell 来运行你的命令。

    exec.Command("sh", "-c", "echo '1 2 3'")
    

    【讨论】:

    • 如此简单的解决方案!是否有适用于 Windows 的同样简单的解决方案?
    • 请记住,这样做会使您的程序更容易受到命令注入漏洞的攻击
    【解决方案2】:

    如何转义引号,然后使用strconv.Unquote 函数?

    executableCommand := strings.Split(strconv.Unquote("git commit -m \"hello world\"", " "))
    executeCommand(executableCommand[0], executableCommand[1:]...)
    cmd := exec.Command(command, args...)
    

    当然,这会因 shell 解释引号的方式而异。

    这是一个简短的演示:

    https://play.golang.org/p/V6uqWcczGV

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-01
      • 2014-12-12
      • 2011-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-22
      • 1970-01-01
      相关资源
      最近更新 更多