package main import ( "fmt" "os/exec" ) func main() { cmd := exec.Command("echo", "Hello World") stdin, err := cmd.StdinPipe() if err != nil { fmt.Println(err) return } defer stdin.Close() if err := cmd.Start(); err != nil { fmt.Println(err) return } _, err = stdin.Write([]byte("Hello\n")) if err != nil { fmt.Println(err) return } if err := cmd.Wait(); err != nil { fmt.Println(err) return } }
package main import ( "fmt" "os/exec" ) func main() { cmd := exec.Command("cat") stdin, err := cmd.StdinPipe() if err != nil { fmt.Println(err) return } defer stdin.Close() if err := cmd.Start(); err != nil { fmt.Println(err) return } input := []byte("Hello World\n") go func() { _, err := stdin.Write(input) if err != nil { fmt.Println(err) return } }() if err := cmd.Wait(); err != nil { fmt.Println(err) return } }In this example, we create a command that prints whatever it receives from standard input (i.e., the "cat" command). We create a pipe for its standard input, write "Hello World" to the pipe in a separate goroutine, and wait for the command to finish. The output of the command will be "Hello World\n".