0 0 0 0


I'm trying to write a perl script which takes the output of colorgcc (or any other script that prints colored text to terminal), adds/removes parts of the string, and then prints the result in the same color as the input string.

The following code will print "Hello World" in front of each line produced by the color_producing_script. The output will be all black, while the input is multicolored. How can I modified this script to conserve the original colors?

open(CMD, "color_producing_script |");
while(<CMD>) {
    print 'Hello World' . $_;

I'm using bash terminal.


Per the excellent first comment, this is not a Perl issue per se. Just running color_producing_script | cat strips the color off. So the question can be rephrased to "How do you force color through the pipe?"

Edit 2

It looks like the latest version of gcc (1.3.2) includes the CGCC_FORCE_COLOR environment variable in the if clause, and if it's defined, colorgcc forces color:

export CGCC_FORCE_COLOR=true

Best Answer:

Does color_producing_script change its behavior when it's used in a pipe? Try

color_producing_script | cat

at the command line. It may have an option to force color output even when it is.

The Perl script, colorgcc, is specifically checking to see if output is to a non-tty and skipping the colorization if that's the case.

# Get the terminal type. 
$terminal = $ENV{"TERM"} || "dumb";
# If it's in the list of terminal types not to color, or if
# we're writing to something that's not a tty, don't do color.
if (! -t STDOUT || $nocolor{$terminal})
   exec $compiler, @ARGV
      or die("Couldn't exec");


You could modify the script in one or more of the following ways:

  • comment out the test and make it always produce color output
  • add functionality to support reading an environment variable that sets whether to colorize
  • add functionality to support a color-always option in the ~/.colorgccrc configuration file
  • add functionality to support a color-always command line option that you strip before passing the rest of the options to the compiler

You could also use the expect script unbuffer to create a pseudo-tty like this:

unbuffer gcc file.c | cat

(where cat is a standin recipient).

All of this is based on using colorgcc from the command line. There should be analogs for doing similar things within a Perl script.

Copyright © 2011 Dowemo All rights reserved.    Creative Commons   AboutUs