【发布时间】:2017-05-04 18:02:39
【问题描述】:
我的问题与此类似:How to detect if my shell script is running through a pipe?。不同之处在于我正在编写的脚本是用 Ruby 编写的。
假设我跑步:
./test.rb
我希望标准输出上的文本带有颜色,但是
./test.rb | cat
我希望去掉颜色代码。
【问题讨论】:
我的问题与此类似:How to detect if my shell script is running through a pipe?。不同之处在于我正在编写的脚本是用 Ruby 编写的。
假设我跑步:
./test.rb
我希望标准输出上的文本带有颜色,但是
./test.rb | cat
我希望去掉颜色代码。
【问题讨论】:
使用$stdout.isatty 或更惯用的$stdout.tty?。我创建了一个小 test.rb 文件来演示,内容:
puts $stdout.isatty
结果:
$ ruby test.rb
true
$ ruby test.rb | cat
false
【讨论】:
$stdout.tty?
使用IO#stat.pipe?。
IO#tty? 在 TTY 设备上仅返回 true。
对于 UNIX 风格的管道返回 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
【讨论】: