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.
我需要在Ruby脚本中检查是否存在STDIN输入,就像mysql命令一样。如果没有任何内容指向STDIN,则脚本不应尝试读取STDIN。
How can this be done in a cross-platform way?
如何以跨平台的方式完成?
1 个解决方案
#1
25
This is something that's done in Linux a lot:
这是在Linux中做的很多事情:
#!/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
#1
25
This is something that's done in Linux a lot:
这是在Linux中做的很多事情:
#!/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