Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if a Ruby script is running through a shell pipe?

Tags:

shell

ruby

pipe

My question is similar to this one: How to detect if my shell script is running through a pipe?. The difference is that the script I’m working on is written in Ruby.

Let’s say I run:

./test.rb

I expect text on stdout with color, but

./test.rb | cat

I expect the color codes to be stripped out.

like image 554
steakunderscore Avatar asked May 04 '17 18:05

steakunderscore


Video Answer


2 Answers

Use $stdout.isatty or more idiomatically, $stdout.tty?. I created a little test.rb file to demonstrate, contents:

puts $stdout.isatty

Results:

$ ruby test.rb
true

$ ruby test.rb | cat
false

Reference: https://ruby-doc.org/core/IO.html#method-i-isatty

like image 146
Derek Wright Avatar answered Oct 08 '22 13:10

Derek Wright


Use IO#stat.pipe?. IO#tty? returns true only on a TTY device. Returns false for UNIX-style pipes (see "man 2 pipe").

 $ echo "something" | ruby -e 'puts $stdin.stat.pipe?'
true
 $ echo "something" | ruby -e 'puts $stdin.tty?'
false
 $ ruby -e 'puts $stdin.tty?'
true
like image 27
Kurt Stephens Avatar answered Oct 08 '22 14:10

Kurt Stephens