如何检测一个 Ruby 脚本是否通过 shell 管道运行?

7

我的问题与这个类似:如何检测我的shell脚本是否通过管道运行?。不同之处在于,我正在使用Ruby编写脚本。

假设我运行:

./test.rb

我希望在标准输出中看到有颜色的文本,但是

./test.rb | cat

我期望颜色代码被去除。
2个回答

14

使用$stdout.isatty或者更加惯用的$stdout.tty?来进行判断。我创建了一个小的test.rb文件来演示,内容如下:

puts $stdout.isatty

结果:

$ ruby test.rb
true

$ ruby test.rb | cat
false

参考资料:https://ruby-doc.org/core/IO.html#method-i-isatty


3
或者更通俗的说:$stdout.tty? - Holger Just

5
使用IO#stat.pipe?IO#tty?仅在TTY设备上返回true。
对于类UNIX的pipes,它会返回false(参见“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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接