Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you automatically colorize program outputs in a bash shell?

Tags:

bash

colors

pipe

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

vs.

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.

like image 716
Lin Avatar asked Jul 06 '09 04:07

Lin


1 Answers

#!/bin/sh
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.

like image 50
ephemient Avatar answered Nov 04 '22 16:11

ephemient