How to detect if a Ruby script is running through

2019-07-10 05:09发布

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.

标签: ruby shell pipe
1条回答
虎瘦雄心在
2楼-- · 2019-07-10 05:39

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

查看更多
登录 后发表回答