2016-07-14 81 views
4

我试图用go执行一个命令。Golang:使用它的参数执行一个命令

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',因为在命令行中使用" "被分割。

任何想法,使其工作?

回答

8

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

exec.Command("sh", "-c", "echo '1 2 3'") 
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