Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I split a string and use it as function arguments in Go?

Tags:

go

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?

like image 762
Steven Lu Avatar asked Jan 18 '26 14:01

Steven Lu


1 Answers

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

like image 152
Dave Avatar answered Jan 20 '26 20:01

Dave