Detection of redirection, possible?

S

Shannon Fang

Hi All,

How can I detect a ruby program's stdio has been redirected? I would like to
do this:

puts "show message to user"
$stdin.gets unless $stdin.redirected?

This way, if the program runs normally, it show message and wait for user
interaction, if it is redirected to a file, then just puts to that file
without wating for user intervention.

Thanks!
Shannon
 
E

Eric Hodel

Hi All,

How can I detect a ruby program's stdio has been redirected? I
would like to do this:

puts "show message to user"
$stdin.gets unless $stdin.redirected?

This way, if the program runs normally, it show message and wait
for user interaction, if it is redirected to a file, then just puts
to that file without wating for user intervention.

I think you want IO#tty?:

$ ruby -e 'p $stdin.tty?'
true
$ ruby -e 'p $stdin.tty?' < /dev/zero
false
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,763
Messages
2,569,562
Members
45,038
Latest member
OrderProperKetocapsules

Latest Threads

Top