Detect if a command is piped or not

Viewed 2629

Is there a way to detect if a command in go is piped or not?

Example:

cat test.txt | mygocommand #Piped, this is how it should be used
mygocommand # Not piped, this should be blocked

I'm reading from the Stdin reader := bufio.NewReader(os.Stdin).

2 Answers

same can be done with performing a similar bitwise operation with ModeNamedPipe

package main

import (
        "fmt"
        "os"
)

func main() {
        fi, err := os.Stdin.Stat()
        if err != nil {
                panic(err)
        }

        if (fi.Mode() & os.ModeNamedPipe) != 0 {
                fmt.Println("data is from pipe")
        } else {
                fmt.Println("data is from terminal")
        }
}
Related