Detect if a command is piped or not

2020-05-26 13:24发布

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).

标签: go pipe
1条回答
看我几分像从前
2楼-- · 2020-05-26 13:52

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)

查看更多
登录 后发表回答