package main
import (
"fmt"
"os"
"os/exec"
"strings"
)
func main() {
// 1. Create an *exec.Cmd
// cmd := exec.Command("go", "version")
// // Stdout buffer
// cmdOutput := &bytes.Buffer{}
// // Attach buffer to command
// cmd.Stdout = cmdOutput
// // Execute command
// printCommand(cmd)
// err := cmd.Run() // will wait for command to return
// printError(err)
// // Only output the commands stdout
// printOutput(cmdOutput.Bytes())
// 2. Create an *exec.Cmd
cmd := exec.Command("go", "version")
// Combine stdout and stderr
printCommand(cmd)
output, err := cmd.CombinedOutput()
printError(err)
printOutput(output)
}
func printCommand(cmd *exec.Cmd) {
fmt.Printf("==> Executing: %s\n", strings.Join(cmd.Args, " "))
}
func printError(err error) {
if err != nil {
os.Stderr.WriteString(fmt.Sprintf("==> Error: %s\n", err.Error()))
}
}
func printOutput(outs []byte) {
if len(outs) > 0 {
fmt.Printf("==> Output: %s\n", string(outs))
}
}
출처: https://www.darrencoxall.com/golang/executing-commands-in-go