How to create an os.exec command structure from a string with spaces

I want my method to get the exec command as a string. If the input string has spaces, how to split it into cmd, args for os.exec?

The documentation says about creating my Exec.Cmd structure, e.g.

cmd := exec.Command("tr", "a-z", "A-Z")

This works great:

a := string("ifconfig")
cmd := exec.Command(a)
output, err := cmd.CombinedOutput()
fmt.Println(output) // prints ifconfig output

This fails:

a := string("ifconfig -a")
cmd := exec.Command(a)
output, err := cmd.CombinedOutput()
fmt.Println(output) // 'ifconfig -a' not found

I tried strings.Split (a) but got an error: I can not use (type [] string) as a type string in the argument to exec.Command

+4
source share
2 answers

Please check: https://golang.org/pkg/os/exec/#example_Cmd_CombinedOutput

Your code crashes because exec.Command expects the command arguments to be separated from the actual command name.

strings.Split signature (https://golang.org/pkg/strings/#Split):

func Split(s, sep string) []string

:

command := strings.Split("ifconfig -a", " ")
if len(command) < 2 {
    // TODO: handle error
}
cmd := exec.Command(command[0], command[1:]...)
stdoutStderr, err := cmd.CombinedOutput()
if err != nil {
    // TODO: handle error more gracefully
    log.Fatal(err)
}
// do something with output
fmt.Printf("%s\n", stdoutStderr)
+5
args := strings.Fields("ifconfig  -a ")
exec.Command(args[0], args[1:]...)

strings.Fields()

...

+4

Source: https://habr.com/ru/post/1674149/


All Articles