package spawn import ( "fmt" "io" "os/exec" ) func Spawn() { // Cmd object represents the external process dateCmd := exec.Command("date") // Runs and wait for it to finish, output collected dateOut, err := dateCmd.Output() if err != nil { panic(err) } fmt.Println("> date") fmt.Println(string(dateOut)) _, err = exec.Command("date", "-x").Output() if err != nil { switch e := err.(type) { case *exec.Error: fmt.Println("failed executing:", err) case *exec.ExitError: fmt.Println("command exit code:", e.ExitCode()) default: panic(err) } } grepCmd := exec.Command("grep", "hello") grepIn, _ := grepCmd.StdinPipe() grepOut, _ := grepCmd.StdoutPipe() grepCmd.Start() grepIn.Write([]byte("hello world\ngoodbye grep\nI am Jin, hello")) grepIn.Close() grepBytes, _ := io.ReadAll(grepOut) grepCmd.Wait() fmt.Println("> grep hello") fmt.Println(string(grepBytes)) 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)) }