21

I need to check for the presence of STDIN input in a Ruby script, like the mysql command can. If nothing is being directed to STDIN, then the script should not attempt to read STDIN.

How can this be done in a cross-platform way?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
dan
  • 43,914
  • 47
  • 153
  • 254

1 Answers1

33

This is something that's done in Linux a lot:

#!/usr/bin/env ruby

str = (STDIN.tty?) ? 'not reading from stdin' : $stdin.read
puts str

>> $ ruby test.rb 
>> not reading from stdin
>> $ echo "reading from stdin" | ruby test.rb 
>> reading from stdin
the Tin Man
  • 158,662
  • 42
  • 215
  • 303