在golang中运行系统命令就像在perl中运行系统命令

I am trying to run the system commands in golang. I want the stdout to be printint directly out onto the screen. In golang I use the following now :

out, err := exec.Command(cmd).Output()
    if err != nil {
        fmt.Println("error occured")
        fmt.Printf("%s", err)
   }

Here I am storing the output into "out" variable and then printing that onto the screen. But I want something which prints as a normal shell command like the system() command in perl.

in perl:

system("ls -l");

We don't need to store anything here.

is there some command in golang which mimics exactly the system() cmd in perl.

I can't see any built in options for what you want - but a 7 line function would suffice, I believe:

func system(cmd string, arg ...string) {
    out, err := exec.Command(cmd, arg...).Output()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(string(out))
}

Then you can simply call it:

system("ls", "-l")

So a working full example would be:

package main

import (
    "fmt"
    "log"
    "os/exec"
)

func main() {
    system("ls", "-l")
}

func system(cmd string, arg ...string) {
    out, err := exec.Command(cmd, arg...).Output()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(string(out))
}

function Command returns the Cmd struct which has Stdout field among others.
You just have to attach OS Stdout to Cmd's Stdout

Example:

cmd := exec.Command("date") // no need to call Output method here
cmd.Stdout = os.Stdout // instead use Stdout
cmd.Stderr = os.Stderr // attach Stderr as well

err := cmd.Run()
if err != nil {
    log.Fatal(err)
}

Refer: Command documentation