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.
Code
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
Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.