The simplest way to run an external command is to use exec.Command followed by the Output method.
import ( "fmt" "os/exec")// Create a command that runs datedateCmd := exec.Command("date")// Run the command and collect outputdateOut, err := dateCmd.Output()if err != nil { panic(err)}fmt.Println("> date")fmt.Println(string(dateOut))
The exec.Command helper creates an object to represent the external process. The Output method runs the command, waits for it to finish, and collects its standard output.
When you need to run a complete command string (instead of separate command and arguments), use bash with the -c option:
lsCmd := exec.Command("bash", "-c", "ls -a -l -h")lsOut, err := lsCmd.Output()if err != nil { panic(err)}fmt.Println("> ls -a -l -h")fmt.Println(string(lsOut))
When spawning commands, you need to provide an explicitly delineated command and argument array. You cannot just pass in one command-line string directly to exec.Command.
$ go run spawning-processes.go> dateThu 05 May 2022 10:10:12 PM PDTcommand exit rc = 1> grep hellohello grep> ls -a -l -hdrwxr-xr-x 4 mark 136B Oct 3 16:29 .drwxr-xr-x 91 mark 3.0K Oct 3 12:50 ..-rw-r--r-- 1 mark 1.3K Oct 3 16:28 spawning-processes.go