Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if a command is piped or not

Tags:

pipe

go

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

like image 624
Florian Avatar asked May 12 '17 22:05

Florian


2 Answers

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)

like image 62
user513951 Avatar answered Oct 13 '22 19:10

user513951


same can be done with performing a similar bitwise operation with ModeNamedPipe

package main

import (
        "fmt"
        "os"
)

func main() {
        fi, err := os.Stdin.Stat()
        if err != nil {
                panic(err)
        }

        if (fi.Mode() & os.ModeNamedPipe) != 0 {
                fmt.Println("data is from pipe")
        } else {
                fmt.Println("data is from terminal")
        }
}
like image 1
Amila Kumaranayaka Avatar answered Oct 13 '22 19:10

Amila Kumaranayaka