44

I need a command line utility to behave different if some string is piped into its STDIN. Here's some minimal example:

package main // file test.go

import (
    "fmt"
    "io/ioutil"
    "os"
)

func main() {
    bytes, _ := ioutil.ReadAll(os.Stdin)

    if len(bytes) > 0 {
        fmt.Println("Something on STDIN: " + string(bytes))
    } else {
        fmt.Println("Nothing on STDIN")
    }
}

This works fine if you call it like that:

echo foo | go run test.go

If test.go is called without anything on STDIN, the thing stucks at...

bytes, _ := ioutil.ReadAll(os.Stdin)

... waiting for EOF.

What do I need to do to get this going?

Thanks in advance!

6
  • did you try wrapping stdin with a bufio.reader or something like that? or maybe using peek to see if there's anything to read? Mar 30, 2014 at 14:11
  • read the doc: ReadAll goes on until there's an error or EOF, so ask yourself: was there an error reading from stdin? EOF? (you can send EOF in a terminal, it control-D on unix, something else on windows)
    – loreb
    Mar 30, 2014 at 17:03
  • @loreb I read the docs. You describe the same stuff I did, there is nothing new mentioned.
    – sontags
    Mar 30, 2014 at 17:09
  • @sontags uh? Sorry, I must have misunderstood your question then. It doesn't see EOF because, well, obviously the keyboard is still there, so you must either send an EOF from the keyboard (control-D in unix) or read the output one piece at a time, line by line or whatever.
    – loreb
    Mar 30, 2014 at 17:15
  • 3
    possible duplicate of Determine if Stdin has data with Go
    – Kluyg
    Mar 31, 2014 at 3:56

5 Answers 5

68

I solved this by using os.ModeCharDevice:

stat, _ := os.Stdin.Stat()
if (stat.Mode() & os.ModeCharDevice) == 0 {
    fmt.Println("data is being piped to stdin")
} else {
    fmt.Println("stdin is from a terminal")
}
3
  • 1
    tested this, if you pipe stdin (ie. ./foo < /dev/null) from /dev/null you will think there is no stdin. That seems correct to me, since there is nothing to get from /dev/null anyways...
    – ostler.c
    Nov 1, 2014 at 21:37
  • 5
    I like this solution better than @NickCraig-Wood because it uses standard go packages.
    – coffekid
    Dec 1, 2015 at 14:46
  • 1
    At least for me, this solution does not work under Git Bash on Windows, which is the default bash for Github Actions. This solution always prints "data is being piped to stdin" regardless of whether I run 'echo foo | go run .' or just 'go run .' without piping anything. I do get good behavior for those two cases with this answer here.
    – thepudds
    Nov 17, 2022 at 16:34
20

Use the IsTerminal function from code.google.com/p/go.crypto/ssh/terminal (which was exp/terminal) or the Isatty function from github.com/andrew-d/go-termutil which is a much more focussed package.

If stdin is a terminal/tty then you aren't being piped stuff and you can do something different.

Here is an example

package main

import (
    "fmt"
    termutil "github.com/andrew-d/go-termutil"
    "io"
    "os"
)

func main() {
    if termutil.Isatty(os.Stdin.Fd()) {
        fmt.Println("Nothing on STDIN")
    } else {
        fmt.Println("Something on STDIN")
        io.Copy(os.Stdout, os.Stdin)
    }
}

Testing

$ ./isatty 
Nothing on STDIN
$ echo "hello" | ./isatty 
Something on STDIN
hello
$ (sleep 1 ; echo "hello") | ./isatty 
Something on STDIN
hello
3
  • Could you please provide an example?
    – sontags
    Apr 1, 2014 at 19:16
  • @sontags example provided! Apr 1, 2014 at 19:37
  • FWIW, this did not work under Git Bash on Windows. (Neither andrew-d/go-termutil nor the golang.org terminal package worked properly in that case).
    – thepudds
    Nov 20, 2022 at 21:18
3

If none of the above works for you, try this way:

stat, err := os.Stdin.Stat()
if err != nil {
    return nil, fmt.Errorf("you have an error in stdin:%s", err)
}
if (stat.Mode() & os.ModeNamedPipe) == 0 {
    return nil, errors.New("you should pass smth to stdin")
}

It worked for me in both darwin (Mac OS) and linux (Ubuntu).

1
  • $ go run sotest.go < sotest.go results in you should pass smth to stdin. The answer with ModeCharDevice behaves as expected.
    – Ondrej
    Dec 12, 2017 at 8:23
1

This does it:

package main // file test.go

import (
    "bufio"
"fmt"
    "os"
)

func main() {
    in := bufio.NewReader(os.Stdin)
    stats, err := os.Stdin.Stat()
    if err != nil {
        fmt.Println("file.Stat()", err)
    }

    if stats.Size() > 0 {
        in, _, err := in.ReadLine()
        if err != nil {
            fmt.Println("reader.ReadLine()", err)
        }
        fmt.Println("Something on STDIN: " + string(in))
    } else {
        fmt.Println("Nothing on STDIN")
    }
}

Thanks @Kluyg !

1
  • 4
    This doesn't work ( sleep 1 ; echo "hello" ) | ./test, printing Nothing on STDIN. I don't think you'll get this approach to work reliably. Apr 1, 2014 at 18:46
0

The other answers here did not seem to work under Git Bash on Windows, which is the default bash for GitHub Actions on Windows. isTerminal from golang.org/x/term also did not seem to work.

For me, using https://github.com/mattn/go-isatty seems to work across platforms, including Git Bash / cygwin / MinGW on Windows.

Example usage (playground link):

func main() {
    if isatty.IsTerminal(os.Stdin.Fd()) || isatty.IsCygwinTerminal(os.Stdin.Fd()) {
        fmt.Println("stdin is terminal, nothing on os.Stdin")
        return
    }

    // stdin might or might not have data, but given it is not a terminal,
    // we should be able to read from it.
    //
    // Some examples:
    //    echo foo | go run .     # we can read "foo" from os.Stdin
    //    go run . < /dev/null    # we can read os.Stdin, but it is empty
    fmt.Println("stdin is not a terminal and we can read it")
    io.Copy(os.Stdout, os.Stdin)
}

Note that this is answering "Can I read from os.Stdin (which might be zero length)?", and not "Is there non-empty data in os.Stdin?". At least for my use case, the first form of the question is useful where "zero length data" is a type of input data that is OK to read.

I would be curious to hear if it does not work for someone else (including what platform).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.