BASH in colors

Problem

When scripting some tasks it is always better to use clear marking of what is OK (in green) and what is not OK (in Red). Now this was easy with simple colors but we sometimes require more than 2 colours.

Escape characters

As often, I saw a good trick and Copy-Pasted it without asking myself anything further.

Today every shell scripts (99,9% of the time bash) are like what follows.

#!/bin/bash

# Author     : "Thomas Lionel SMETS"
# Copyrights : "All rights reserved 2006-2021, A3-SYSTEM srl-bv"
# #####################################################################

#    .---------- constant part!
#    vvvv vvvv-- the code from above
RED='\033[0;31m'
NC='\033[0m' # No Color
GREEN='\033[0;32m'

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
#
# This script ensure that the database is updated
#
NOW=`date +%Y-%m-%d.%H:%M:%S`

printf " * ******************************************************************************************************** * \n"
printf " *  Make migrations                                                                                         * \n"
printf " * ******************************************************************************************************** * \n"
./manage.py makemigrations
RET_CODE=$?
if [ $RET_CODE -eq 0 ];
then
    printf  "./manage.py makemigrations  --> ${GREEN}OK${NC} \n"
else
    printf "./manage.py makemigrations. Code returned : ${RED} ${RET_CODE} ${NC} \n\n"
    exit 2
fi

printf " * ******************************************************************************************************** * \n"
printf " *  Migrate                                                                                                 * \n"
printf " * ******************************************************************************************************** * \n"
./manage.py migrate
RET_CODE=$?
if [ $RET_CODE -eq 0 ];
then
    printf  "./manage.py migrate  --> ${GREEN}OK${NC} \n"
else
    printf "./manage.py migrate. Code returned : ${RED} ${RET_CODE} ${NC}"
    exit 3
fi

But even more

I was very surprised when PyCharm complained about my code ... My very own code was questionnable. It came under the SC2059 comment . There is no possibility to take a screenshot from the overlay displayed by PyCharm...

It said :

Don't use variables in the printf format string. Use printf "..%s.." "$foo". See SC2059.

So the line :

printf "./manage.py migrate. Code returned : ${RED} ${RET_CODE} ${NC}"

should in fact be :

printf "./manage.py migrate. Code returned : ${RED} %s ${NC}" "$RET_CODE"

I have never been confronted with the issue but my scripts & style will soon change !

References

  • [1] Wikipedia on the matter.
  • [2] A thorough reference especially on compatibility with different terminals.
  • [3] SC2059 on how to place the variables in script to avoid misinterpretation of the ESCape characters.