package main import ( "fmt" "os/exec" ) func main() { cmd := exec.Command("echo", "Hello World!") output, err := cmd.Output() if err != nil { fmt.Println(err) } fmt.Println(string(output)) }
package main import ( "fmt" "os/exec" ) func main() { cmd := exec.Command("ls") stdout, err := cmd.StdoutPipe() if err != nil { fmt.Println(err) return } if err := cmd.Start(); err != nil { fmt.Println(err) return } buf := make([]byte, 1024) for { n, err := stdout.Read(buf) if err != nil { fmt.Println(err) return } if n == 0 { break } fmt.Print(string(buf[:n])) } if err := cmd.Wait(); err != nil { fmt.Println(err) return } }In this example, we are creating a new command called "ls" and using the `cmd.StdoutPipe()` function to get a read-only file stream of the command's output. We then start the command using the `cmd.Start()` function and read from the file stream in a loop until there is no more output. Finally, we wait for the command to finish using the `cmd.Wait()` function. Package library: os/exec.