Golang: Running a command with arguments

I am trying to execute a command using go.

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

But here is what I get

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

This is due to the fact that it -mreceives only 'hello, and not 'hello world', since the command line is split using " ".

Any idea to make it work?

+4
source share
2 answers

What you want is actually hard to achieve without the help of a shell that interprets quotation marks, etc. This way you can use shell to execute your command.

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

How to avoid quotes, then use strconv.Unquote function ?

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

, , .

:

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

+2

All Articles