Bash: How to use colors in your tail output

Updated . Posted . Visible to the public.

Sometimes it's nice to have some coloring in your logs for better readability. You can output your logs via tail Show archive.org snapshot and pipe this through sed Show archive.org snapshot to add ANSI color annotations (which your console then interprets).

To print a log (e.g. rails log) and color all lines containing "FATAL" in red and all lines with "INFO" in green:

tail -f /path/to/log | sed --unbuffered -e 's/\(.*INFO.*\)/\o033[32m\1\o033[39m/' -e 's/\(.*FATAL.*\)/\o033[31m\1\o033[39m/'

Here are the most common color codes:

Color Font Background
Black \033[30m \033[40m
Red \033[31m \033[41m
Green \033[32m \033[42m
Orange \033[33m \033[43m
Blue \033[34m \033[44m
Magenta \033[35m \033[45m
Cyan \033[36m \033[46m
Light gray \033[37m \033[47m
Use default \033[39m \033[49m

There are even more colors than this, see this epic SO answer for more details Show archive.org snapshot !

Important

Remember to restore the default color after the content you want colored.

As typing this is kind of cumbersome, you may want to add a bash alias Show archive.org snapshot .

Side note: if you have colored output and want to remove the color annotations, see this card

Judith Roth
Last edit
Judith Roth
License
Source code in this card is licensed under the MIT License.
Posted by Judith Roth to makandra dev (2020-03-17 16:44)