Exec Command Reads Piped Stdin

Feed a child process through cmd.Stdin with any io.Reader, avoiding temp files while the command consumes the data as a stream.

GoCli Tooling

Code

gosnippet
20 lines
package main

import (
	"fmt"
	"os/exec"
	"strings"
)

func main() {
	// Stdin 接任意 io.Reader:管道喂数据,无需临时文件
	cmd := exec.Command("tr", "a-z", "A-Z")
	cmd.Stdin = strings.NewReader("deploy notes\n")

	out, err := cmd.Output()
	if err != nil {
		fmt.Println("run failed:", err)
		return
	}
	fmt.Printf("piped: %s", out)
}

Walkthrough

All of the logic lives in the function main.

Error handling is inline: 1 place test err != nil and branch immediately.

Caveats

  • Zero installs — the standard library is all it touches.

Applying it

The entry-point signature is func main()

The output carries labels — run failed:, piped: — when the file runs.

Statements that matter

if err != nil {
	fmt.Println("run failed:", err)
	return
}

Interactive Tools for This Topic

FAQ

What does Exec Command Reads Piped Stdin print when run?
Run it as a complete program — the output lines carry labels such as `run failed:`, `piped:`.