I want my method to receive a command to exec as a string. If the input string has spaces, how do I split it into cmd, args for os.exec?
The documentation says to create my 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), but receive an error message: cannot use (type []string) as type string in argument to exec.Command
args := strings.Fields("ifconfig -a ")
exec.Command(args[0], args[1:]...)
strings.Fields() splits on whitespace, and returns a slice
...
expands slice into individual string arguments
Please, check out: https://golang.org/pkg/os/exec/#example_Cmd_CombinedOutput
Your code fails because exec.Command expects command arguments to be separated from actual command name.
strings.Split signature (https://golang.org/pkg/strings/#Split):
func Split(s, sep string) []string
What you tried to 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)
}
// do something with output
fmt.Printf("%s\n", stdoutStderr)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With