Colorize shell output

oleber's Avatar author of Colorize shell output
This is an article on Colorize shell output in Perl.
Rated 5.00 By 3 users
Many programs use the STDOUT to produce some normal output and the STDERR to show the errors. I'm actually working with the g++ that do this and a question appeared.

Wouldn't be nice to see it with different colors?

Code: Perl
#!/usr/bin/perl

use strict;
use warnings;

use IPC::Open3;
use IO::Select;
use Term::ANSIColor qw(:constants);

$|++;

my $pid;
eval { $pid=open3(*WRITE, *READ, *ERROR, @ARGV); };

if (!$pid) {
    # if we get here, the fork succeeded, but the exec (likely) failed...
    my $err = $@ ? $@ : "unknown error";
    # exit child in any case
    die "Error: Could not execute: $err";
} else {
    close(*WRITE);
    my $selector=IO::Select->new();
    $selector->add(*READ, *ERROR);
    while(my @ready=$selector->can_read()) {
        foreach my $fh (@ready) {
            my $count = sysread($fh, my $text, 1024);
            $selector->remove($fh) if not $count;

            if(fileno($fh)==fileno(*READ)) {
                print($text);
            } elsif(fileno($fh)==fileno(*ERROR)) {
                print(RED, $text, RESET);
            }
        }
    }
}
way of use
Code:
colorize g++ file.cpp
Useful modules.

use IPC::Open3; : allow to run shell commands and get the STDIN, STDOUT, STDERR.
use IO::Select; : check if a handler has something to be read.
use Term::ANSIColor qw(:constants); : helps to do the colorize.
0
#anna's Avatar, Join Date: Oct 2007
Newbie Member
Another Useful modules today. Thanks.

Last edited by shabbir; 10Oct2007 at 11:50.. Reason: Confine links to signature
0
oleber's Avatar, Join Date: Apr 2007
Go4Expert Member
Did you like this? look to the new version:

http://sites.google.com/site/oleberp...ternal-program