2017-05-12 5 views
4

goのコマンドがパイプされているかどうかを検出する方法はありますか?コマンドがパイプされているかどうかを検出する

例:私は標準入力reader := bufio.NewReader(os.Stdin)から

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

読んでいます。

+1

なぜあなたはそれをブロックしますか?誰かが手作業で端末に入力を入力したり、コピーしたり、何かをコピーしたりするのは実際には問題なのでしょうか? – user2357112

+1

あなたはこれをすでに見てきたかもしれませんが、ここにはシェルスクリプトに関する疑問の行があります:http://stackoverflow.com/questions/911168/how-to-detect-if-my-shell-script-is-running-通し番号 –

+0

@ user2357112 EOFがないので、ユーザーの入力は決して終わらないでしょうか? – Florian

答えて

3

os.Stdin.Stat()を使用してこれを行うことができます。 (https://www.socketloop.com/tutorials/golang-check-if-os-stdin-input-data-is-piped-or-from-terminalから適応)

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") 
    } 
} 

+1

メソッドボディから 'fi、_:= os.Stdin.Stat()'を定義することはできませんが、mainメソッドで使用すると動作します。ありがとう! – Florian

+0

おっと、それは単にタイプミスでした。今修正されました。 –