7

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.

steakunderscore
  • 1,076
  • 9
  • 18

2 Answers2

13

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

Holger Just
  • 52,918
  • 14
  • 115
  • 123
Derek Wright
  • 1,452
  • 9
  • 11
5

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
Kurt Stephens
  • 61
  • 1
  • 2