How to Pipe a Command Through a Color Filter in Bash

bashcolorsterminal

Does something like this exist in Unix?

$ echo "this should show in red" | red
$ echo "this should show in green" | green
$ echo "this should show in blue" | blue

Here I don't mean for literal color code text to come up (to be pasted in a file, for example). I just mean for the text to actually show up in the terminal as that color. Is this possible?

Best Answer

Here's a little script that does just that. Save this as color in a directory in your $PATH (for example, ~/bin if that's in your $PATH):

#!/usr/bin/env perl

use strict;
use warnings;
use Term::ANSIColor; 

my $color=shift;
while (<>) {
    print color("$color").$_.color("reset");
} 

Then, pass your text through the script, giving . as the pattern to match and specifying a color:

screenshot of a terminal running the script

The supported colors depend on the abilities of your terminal. For more details, see the documentation of the Term::ANSIColor package.