How to Execute Linux Commands in Golang
If you want to execute Linux commands in Golang, you can use exec.Command from the os/exec package:
cmd := exec.Command("echo", "hello world")
res, _ := cmd.CombinedOutput()
fmt.Println(string(res))
The first argument is the command, and the rest are its arguments — each as a separate string. Don’t pass the whole command as a single string like you might in other languages.
CombinedOutput() captures both stdout and stderr. If you need them separately, use cmd.Output() for just stdout, or set cmd.Stdout and cmd.Stderr to different writers.
In production code, always check the error return value. A non-zero exit code from the command will come back as an *exec.ExitError, which you can inspect to get the exit code and stderr output.
Don’t forget to import "os/exec" and "fmt" at the top of your file.