8

I'm 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 because -m gets 'hello only and not 'hello world' since the command line is split using " ".

Any idea to make it work?

2 Answers 2

17

What you want is actually hard to achieve without help of shell that interprets quotes etc. So you may use shell to run your command.

exec.Command("sh", "-c", "echo '1 2 3'")
Sign up to request clarification or add additional context in comments.

2 Comments

Such a simple solution! Is there an equivalently simple solution for Windows?
Keep in mind doing something like this can make your program more vulnerable to command injection vulnerabilities
3

What about to escape the quotes, then use the strconv.Unquote function?

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

Of course this will vary of how shell will interpret quotes.

Here is short demonstration:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.