Logo
Published on

Nice logs - A Simple Bash Trick to Boost Readability

Authors
  • avatar
    Name
    Filipe "Hegaja" Oliveira
    Twitter
    @hegaja

I’ve always been fascinated by how colors can enhance data analysis. In a previous post, I mentioned a grep script I use where each keyword is highlighted in its own color: a simple trick that makes parsing logs much easier.

When dealing with logs, even a bit of visual aid can make a big difference. For example, error messages like FAIL or ERROR in bold red immediately catch your eye, while a green OK gives you instant peace of mind. That’s the kind of feedback I want in my scripts.

Color in the Terminal: How It Works

To get this working, I need to understand how the terminal interprets special sequences for text formatting. Thankfully, Bash makes this easy with escape sequences.

Here’s the function I use to colorize output:

function logColor
{
	echo -e "\e[1;${2}m${1}\e[0m"
}

Breakdown:

  1. echo -e -> enables interpretation of escape sequences.
  2. \e[1; -> sets the text to bold.
  3. $2m -> applies the color code passed as the second argument.
  4. $1 -> is the message.
  5. \e[0m -> resets formatting after the message.

Quick Example

Let’s say I want to print my name in blue:

echo -e "\e[1;34mFILIPE\e[0m"
You’ll see FILIPE in bold blue in your terminal. Printscreen of the terminal with my name uin blue

Creating some cool functions

With the logColor function ready, I want to create helper functions for different log levels like warnings, errors, and success messages.

For example, here’s how I show warnings in yellow:

function messageWarning
{
	logColor "\n${1}\n" $YELLOW
}

The color palete follows the ANSI code, and you can find it easy online. I use this palete:

RED=31
GREEN=32
YELLOW=33
BLUE=34
MAGENTA=35
CYAN=36
WHITE=37

What’s Next?

In the next post, I plan to talk about the script I developed to use in my daily work at Volvo cars. The idea is to automate some steps (building/flashing/testing) or just to perform some supportive work like generating a xml file from the current paired Android device.