i want method receive command exec string. if input string has spaces, how split cmd, args os.exec?
the documentation says create exec.cmd struct like
cmd := exec.command("tr", "a-z", "a-z")
this works fine:
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), receive error message: cannot use (type []string) type string in argument exec.command
please, check out: https://golang.org/pkg/os/exec/#example_cmd_combinedoutput
your code fails because exec.command expects command arguments separated actual command name.
strings.split signature (https://golang.org/pkg/strings/#split):
func split(s, sep string) []string
what tried achieve:
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) } // output fmt.printf("%s\n", stdoutstderr)
Comments
Post a Comment