R – How to automatically colorize program outputs in a bash shell


I want to take any program that outputs to the screen, catch the output, and colorize certain keywords before they are output to the screen. For example, here's the normal program output:

bash# <program>
blah blah blah       <-- this output has no color


bash# <program>
blah blah blah       <-- this output is colorful

Ideally it doesn't matter what the program is. I'm just looking for a good way to incorporate more color into my konsoles.

Edit: Sorry, should've been clear. I'm not trying to just colorize shell script outputs.

Best Solution

redf=$(tput setaf 1)
redb=$(tput setab 1)
reset=$(tput op)
echo "${redf}red${reset} in front, ${redb}red${reset} in back"

See terminfo for a long listing of terminal capabilities. A $TERM with suffix -m (e.g. ansi-m) means the screen is monochrome, but as long as color works, the following string capabilities should be non-empty:

       enter_bold_mode               bold         md        turn on bold (extra
                                                            bright) mode
       enter_italics_mode            sitm         ZH        Enter italic mode
       enter_reverse_mode            rev          mr        turn on reverse
                                                            video mode
       orig_pair                     op           op        Set default pair to
                                                            its original value
       set_a_background              setab        AB        Set background
                                                            color to #1, using
                                                            ANSI escape
       set_a_foreground              setaf        AF        Set foreground
                                                            color to #1, using
                                                            ANSI escape

Colors 0-7 are pretty much standard: black, red, green, yellow, blue, magenta, cyan, white. Beyond that may not exist or may be more variable.