3

I have a string that is separated by spaces, in this example, its a command: ls -al.

Go has a method exec.Command that needs to accept this command as multiple arguments, I call it like so: exec.Command("ls", "-al")

Is there a way to take a arbitrary string, split it by spaces, and pass all of its values as arguments to the method?

4 Answers 4

6

I recently discovered a nice package that handles splitting strings exactly as the shell would, including handling quotes, etc: https://github.com/kballard/go-shellquote

Sign up to request clarification or add additional context in comments.

1 Comment

This should be the accepted answer, every other answer here is wrong.
5

You can pass any []T as a parameter of type ...T using foo... where foo is of type []T: spec

exec.Command is of type:

func Command(name string, arg ...string) *Cmd

In this case you will have to pass 1st argument (name) directly and you can expand the rest with ...:

args := strings.Fields(mystr) //or any similar split function
exec.Command(args[0], args[1:]...)

1 Comment

This doesn't deal with quoted portions of the input string
0

I can answer the first part of your question — see strings.Fields.

2 Comments

Thanks, haha. Now I just need to pass it along :)
This won't work with quoted arguments.
0

Yep. An example:

func main() {
    arguments := "arg1 arg2 arg3"

    split := strings.Split(arguments, " ")

    print(split...)
}

func print(args...string) {
    fmt.Println(args)
}

1 Comment

This won't work if the arguments contain spaces (either because they are quoted or the spaces are escaped).

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.