Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an os.exec Command struct from a string with spaces

Tags:

go

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

like image 727
clamster Avatar asked Apr 06 '17 01:04

clamster


Video Answer


2 Answers

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

like image 129
Mark Avatar answered Oct 07 '22 11:10

Mark


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)
like image 42
mwarzynski Avatar answered Oct 07 '22 12:10

mwarzynski