9

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.

2 Answers 2

16

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

Sign up to request clarification or add additional context in comments.

1 Comment

or more idiomatic: $stdout.tty?
6

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.