How to Execute External Commands in Go with os/exec

Execute external commands in Go using the os/exec package's Command function and Run or Output methods.

Use exec.Command to create a command struct, then call Run, Output, or CombinedOutput to execute it. The Run method executes the command and returns an error if it fails, while Output and CombinedOutput return the command's output as a byte slice.

package main

import (
	"fmt"
	"os/exec"
)

func main() {
	cmd := exec.Command("ls", "-l")
	output, err := cmd.CombinedOutput()
	if err != nil {
		fmt.Println("Error:", err)
		return
	}
	fmt.Println(string(output))
}