检测命令是否通过管道传输 [英] Detect if a command is piped or not
本文介绍了检测命令是否通过管道传输的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有一种方法可以检测go中的命令是否通过管道传输?
Is there a way to detect if a command in go is piped or not?
示例:
cat test.txt | mygocommand #Piped, this is how it should be used
mygocommand # Not piped, this should be blocked
我正在从Stdin reader := bufio.NewReader(os.Stdin)
中阅读.
I'm reading from the Stdin reader := bufio.NewReader(os.Stdin)
.
推荐答案
您可以使用os.Stdin.Stat()
进行此操作.
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")
}
}
(改编自 查看全文