Detect if a command is piped or not

后端 未结 1 753
无人及你
无人及你 2021-02-05 16:05

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          


        
相关标签:
1条回答
  • 2021-02-05 17:02

    You can do this using os.Stdin.Stat().

    package main
    
    import (
      "fmt"
      "os"
    )
    
    func main() {
        fi, _ := os.Stdin.Stat()
    
        if (fi.Mode() & os.ModeCharDevice) == 0 {
            fmt.Println("data is from pipe")
        } else {
            fmt.Println("data is from terminal")
        }
    }
    

    (Adapted from https://www.socketloop.com/tutorials/golang-check-if-os-stdin-input-data-is-piped-or-from-terminal)

    0 讨论(0)
提交回复
热议问题