20

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
  • 155,156
  • 41
  • 207
  • 295
dan
  • 41,304
  • 47
  • 143
  • 239

1 Answers1

32

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
  • 155,156
  • 41
  • 207
  • 295