0

I am looking to create a simple unix watch like command using Ruby to run commands. But colours aren't preserved for some commands. For instance, I was able to preserve the colour while executing:

puts %x{ CLICOLOR_FORCE=1 ls -la} 

* flag suggestion by john-c

I am assuming its because the commands switch to a printable text only version when the command is invoked via script, possibly to ease further processing. Have heard of this, but don't have the proper pointer/terms to do a research; is there a way to force the coloured output through a Ruby script? Or 'trick' the commands into thinking its invoked via terminal rather than a script?

I tested without success with the following:

puts %x{ CLICOLOR_FORCE=1 rspec --color test_file.rb  }

I know there is a well established way to go about this using guard-rspec. But I am pursuing this for a gem that I am building and I need the capability to run arbitrary commands with coloured output preserved.

Any help will be greatly appreciated.

Community
  • 1
  • 1
Jikku Jose
  • 18,306
  • 11
  • 41
  • 61

2 Answers2

2

You're correct that the commands you are running switch to a non-colour output when invoked from a script. They detect that their standard output is not a terminal and modify their output accordingly.

Fortunately, you should be able to trick the commands into thinking they are outputting to a terminal by using a pseudo-terminal. You can do this using the PTY module in Ruby.

I took the following from this answer and tested it on Ruby 1.9.3-p392.

require 'pty'

PTY.spawn('ls --color=auto') do |stdin, stdout, pid|
  begin
    stdin.each {|line| print line}
  rescue Errno::EIO
    # End of input
  end
end
Community
  • 1
  • 1
simonwo
  • 3,171
  • 2
  • 19
  • 28
2

Guard runs the command in a subshell using Kernel#system. This works for me:

$ ruby -e "system('ls -la')"

or

$ ruby -e "system('rspec test_file.rb')"
Stefan
  • 109,145
  • 14
  • 143
  • 218
  • Wow thanks it works! I should get to the habit of opening projects that already implements the feature! But, I think I should give credit to the previous one for the answer as its more to the point, despite the fact that I will be using this. Thanks anyways. – Jikku Jose Jun 11 '14 at 17:59