views:

803

answers:

2

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?

+4  A: 

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.

John M
Thanks! I should have noted in the question that I'm actually running a different command (rake spec), but I wanted to be generic. Setting an environment variable led me down the right path though -- I found in rspec's source that one can set RSPEC_COLOR=true to force color even if we're not from a tty.
Brent Dillingham
+2  A: 

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

JD