Golang:使用它的参数执行命令

Golang: Executing a command with it's arguments

我正在尝试使用 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',因为命令行是使用 " " 分割的。

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

如果没有解释引号等的 shell 的帮助,您实际上很难实现您想要的。因此您可以使用 shell 到 运行 您的命令。

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

如何转义引号,然后使用 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