检测命令是否通过管道传输

时间:2017-05-12 22:37:02

标签: go pipe

有没有办法检测go中的命令是否有管道?

示例:

NSLayoutManager

我正在阅读Stdin cat test.txt | mygocommand #Piped, this is how it should be used mygocommand # Not piped, this should be blocked

1 个答案:

答案 0 :(得分:9)

您可以使用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")
    }
}

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