Golang : Split strings into command line arguments
Problem :
You have a string and you want to split the string into command line arguments in Golang.
Solution :
Use the strings.Split()
function to break the string into a splice with each word as element.
For example :
package main
import (
"fmt"
"os/exec"
"strings"
)
func main() {
cmdLine := "ls -la"
//split into a splice
splitArgs := strings.Split(cmdLine, " ")
fmt.Println("The argument is " + cmdLine)
fmt.Println("The first argument is " + splitArgs[0])
fmt.Println("The second argument is " + splitArgs[1])
cmd := exec.Command(splitArgs[0], splitArgs[1:]...)
// capture the exec.Command output
output, err := cmd.Output()
if err != nil {
fmt.Println(err)
}
fmt.Println(string(output))
}
Sample output :
The argument is ls -la
The first argument is ls
The second argument is -la
total 101320
drwxr-xr-x+ 272 sweetlogic staff 9248 Mar 26 11:27 .
drwxr-xr-x 5 root admin 170 Oct 20 17:59 ..
-r-------- 1 sweetlogic staff 7 Oct 24 11:10 .CFUserTextEncoding
-rw-r--r--@ 1 sweetlogic staff 12292 Mar 25 17:36 .DS_Store
See also : Golang : Execute shell command
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+9.4k Golang : How to generate Code 39 barcode?
+6.2k Golang : Handling image beyond OpenCV video capture boundary
+8.1k Golang: Prevent over writing file with md5 hash
+6.7k Golang : How to solve "too many .rsrc sections" error?
+9k Golang : Write multiple lines or divide string into multiple lines
+13.5k Golang : Convert spaces to tabs and back to spaces example
+7.6k Setting $GOPATH environment variable for Unix/Linux and Windows
+7.6k Golang : Ways to recover memory during run time.
+15.5k Golang : Get current time from the Internet time server(ntp) example
+15.3k Golang : How to convert(cast) IP address to string?
+33.4k Golang : All update packages with go get command
+15.3k Golang : Intercept Ctrl-C interrupt or kill signal and determine the signal type