Reputation: 2180
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?
Upvotes: 3
Views: 3962
Reputation: 4694
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
Upvotes: 6
Reputation: 21505
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:]...)
Upvotes: 6
Reputation: 541
Yep. An example:
func main() {
arguments := "arg1 arg2 arg3"
split := strings.Split(arguments, " ")
print(split...)
}
func print(args...string) {
fmt.Println(args)
}
Upvotes: 0