When developing command-line utilities, it's often necessary to distinguish between input being piped from another program or entered interactively. This article addresses how to check if data is present on STDIN in Go.
Consider the following code:
package main import ( "fmt" "io/ioutil" "os" ) func main() { bytes, _ := ioutil.ReadAll(os.Stdin) if len(bytes) > 0 { fmt.Println("Something on STDIN: " + string(bytes)) } else { fmt.Println("Nothing on STDIN") } }
When invoked with piped input (e.g., echo foo | go run test.go), this code correctly identifies the input. However, if called interactively (without piped input), the program indefinitely waits at ioutil.ReadAll(os.Stdin).
To differentiate between piped and non-piped input, utilize os.ModeCharDevice. This mode identifies whether the input is from a terminal or not. If it's not from a terminal, it's likely piped.
stat, _ := os.Stdin.Stat() if (stat.Mode() & os.ModeCharDevice) == 0 { fmt.Println("data is being piped to stdin") } else { fmt.Println("stdin is from a terminal") }
The above is the detailed content of How Can I Detect if Input is Piped to STDIN in Go?. For more information, please follow other related articles on the PHP Chinese website!