如何在go lang中将标志传递给命令?

I have been trying to run a command and parse the output in golang. Here is a sample of what I am trying to do:

package main

import (
        "fmt"
    "os/exec"
)

func main() {
    out,err := exec.Command("ls -ltr").Output()
        if err != nil {
                fmt.Println("Error: %s", err)
        }
    fmt.Printf("%s",out)
}

Now, when I am trying to run "ls -ltr", I get this error:

Error: %s exec: "ls -ltr": executable file not found in $PATH

So, basically go is looking for whole "ls -ltr" in PATH. And it's not there obviously. Is there any way I can pass a flag to any argument?TIA.

You pass arguments to the program by passing more arguments to the function - it's variadic:

out,err := exec.Command("ls","-ltr").Output()

https://golang.org/pkg/os/exec/#Command

This is a pretty common convention with exec-style functions which you will see in most languages. The other common pattern is builders.


Sometimes the layout of arguments you need to pass won't be known at compile-time (though it's not a good idea to send arbitrary commands to the system - stay safe!). If you want to pass an unknown number of arguments, you can use an array with some special syntax:

// Populate myArguments however you like
myArguments := []string{"bar","baz"}

// Pass myArguments with "..." to use variadic behaviour
out,err := exec.Command("foo", myArguments...).Output()