Execute operating system shell command in Go

Here we will see how to execute a shell command in Go. There are multiple ways to execute a shell command. The simple one is like this:

 1package main
 2
 3import (
 4	"os/exec"
 5)
 6
 7func main() {
 8	cmd := exec.Command("ls", "-l")
 9	cmd.Run()
10}

While the above example is good to just execute the command, in a practical situation we need to know the output of the command as well as if there is any error. For that we need to write some more code to capture the stdout and stderr output as below:
 1package main
 2
 3import (
 4	"bytes"
 5	"fmt"
 6	"log"
 7	"os/exec"
 8)
 9
10func main() {
11
12	cmd := exec.Command("ls", "-l")
13	var stdout, stderr bytes.Buffer
14	cmd.Stdout = &stdout
15	cmd.Stderr = &stderr
16	err := cmd.Run()
17	if err != nil {
18		log.Printf("cmd.Run: %s failed: %s\n", err)
19	}
20	outStr, errStr := string(stdout.Bytes()), string(stderr.Bytes())
21	if len(errStr) > 1 {
22		fmt.Printf("out:\n%s\nerr:\n%s\n", outStr, errStr)
23	}
24	
25	fmt.Printf(outStr)
26}

References:


comments powered by Disqus