Brent Dillingham
Brent Dillingham

Reputation: 1038

Color output from shell command in Ruby

Here's a simple Ruby script:

puts `ls -laG`

In OS X's ls, -G is for color.

When run under bash, I get color output. When the above is run from a Ruby script, I don't see color or the ANSI escape sequences in the resulting output.

From what I've read, my guess is it's because the script isn't running as a tty. Is there some way to run the command as if it were being run under a true tty session -- or something like that?

Upvotes: 3

Views: 2165

Answers (2)

JD Frias
JD Frias

Reputation: 4686

According to the man page you can force it by setting CLICOLOR_FORCE.

Upvotes: 3

John M
John M

Reputation: 13229

Looking at the ls man page in OS X, I see a couple of environment variables mentioned. CLICOLOR enables color (like -G) and CLICOLOR_FORCE (forces color even to non-terminal output).

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. In my example, I just used the env command to ensure they're set on the command line. I left off the -G option since CLICOLOR does the equivalent.

Upvotes: 7

Related Questions