()
| 11 | ) |
| 12 | |
| 13 | func main() { |
| 14 | |
| 15 | // We'll start with a simple command that takes no |
| 16 | // arguments or input and just prints something to |
| 17 | // stdout. The `exec.Command` helper creates an object |
| 18 | // to represent this external process. |
| 19 | dateCmd := exec.Command("date") |
| 20 | |
| 21 | // The `Output` method runs the command, waits for it |
| 22 | // to finish and collects its standard output. |
| 23 | // If there were no errors, `dateOut` will hold bytes |
| 24 | // with the date info. |
| 25 | dateOut, err := dateCmd.Output() |
| 26 | if err != nil { |
| 27 | panic(err) |
| 28 | } |
| 29 | fmt.Println("> date") |
| 30 | fmt.Println(string(dateOut)) |
| 31 | |
| 32 | // `Output` and other methods of `Command` will return |
| 33 | // `*exec.Error` if there was a problem executing the |
| 34 | // command (e.g. wrong path), and `*exec.ExitError` |
| 35 | // if the command ran but exited with a non-zero return |
| 36 | // code. |
| 37 | _, err = exec.Command("date", "-x").Output() |
| 38 | if err != nil { |
| 39 | if e, ok := errors.AsType[*exec.Error](err); ok { |
| 40 | fmt.Println("failed executing:", e) |
| 41 | } else if e, ok := errors.AsType[*exec.ExitError](err); ok { |
| 42 | exitCode := e.ExitCode() |
| 43 | fmt.Println("command exit rc =", exitCode) |
| 44 | } else { |
| 45 | panic(err) |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | // Next we'll look at a slightly more involved case |
| 50 | // where we pipe data to the external process on its |
| 51 | // `stdin` and collect the results from its `stdout`. |
| 52 | grepCmd := exec.Command("grep", "hello") |
| 53 | |
| 54 | // Here we explicitly grab input/output pipes, start |
| 55 | // the process, write some input to it, read the |
| 56 | // resulting output, and finally wait for the process |
| 57 | // to exit. |
| 58 | grepIn, _ := grepCmd.StdinPipe() |
| 59 | grepOut, _ := grepCmd.StdoutPipe() |
| 60 | grepCmd.Start() |
| 61 | grepIn.Write([]byte("hello grep\ngoodbye grep")) |
| 62 | grepIn.Close() |
| 63 | grepBytes, _ := io.ReadAll(grepOut) |
| 64 | grepCmd.Wait() |
| 65 | |
| 66 | // We omitted error checks in the above example, but |
| 67 | // you could use the usual `if err != nil` pattern for |
| 68 | // all of them. We also only collect the `StdoutPipe` |
| 69 | // results, but you could collect the `StderrPipe` in |
| 70 | // exactly the same way. |
nothing calls this directly
no outgoing calls
no test coverage detected