dan
dan

Reputation: 45672

How can you check for STDIN input in a Ruby script?

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?

Upvotes: 21

Views: 5861

Answers (1)

the Tin Man
the Tin Man

Reputation: 160631

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

Upvotes: 34

Related Questions