简体   繁体   English

Ruby中shell命令的颜色输出

[英]Color output from shell command in Ruby

Here's a simple Ruby script: 这是一个简单的Ruby脚本:

puts `ls -laG`

In OS X's ls, -G is for color. 在OS X的ls中,-G用于颜色。

When run under bash, I get color output. 在bash下运行时,我得到颜色输出。 When the above is run from a Ruby script, I don't see color or the ANSI escape sequences in the resulting output. 当从Ruby脚本运行上述内容时,我在结果输出中看不到颜色或ANSI转义序列。

From what I've read, my guess is it's because the script isn't running as a tty. 从我读过的,我的猜测是因为脚本没有像tty一样运行。 Is there some way to run the command as if it were being run under a true tty session -- or something like that? 有没有办法运行命令,好像它是在真正的tty会话下运行 - 或类似的东西?

Looking at the ls man page in OS X , I see a couple of environment variables mentioned. 查看OS X中的ls手册页 ,我看到了一些提到的环境变量。 CLICOLOR enables color (like -G) and CLICOLOR_FORCE (forces color even to non-terminal output). CLICOLOR启用颜色(如-G)和CLICOLOR_FORCE(强制颜色甚至非终端输出)。

So I think you'll get what you want with... 所以我想你会得到你想要的......

puts `env CLICOLOR=1 CLICOLOR_FORCE=1 ls -la`

You could set the environment variables in your .profile. 您可以在.profile中设置环境变量。 In my example, I just used the env command to ensure they're set on the command line. 在我的示例中,我只是使用env命令来确保它们在命令行上设置。 I left off the -G option since CLICOLOR does the equivalent. 我没有使用-G选项,因为CLICOLOR做了相同的操作。

根据手册页,您可以通过设置CLICOLOR_FORCE强制它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM