Friday, September 18, 2020

Bring Some Color to Your bash Shell Output

I'm not sure if this is something anyone will find valuable but it's been a neat little addition to my scripting as of late.

For those who have used Cucumber in the past for BDD, one of the visible elements is of course there paradigm of green, yellow and red text that appears for a variety of things in your output on the screen. This division also helps me quickly monitor if something seems out of place or if a command I expect to run completes correctly or not. as I do a lot with shell scripts, I decided to do some research and see if I could add a bit of that green, yellow, red (and for some variety I even added blue to the mix). Here's how you can do that.

First, the echo command allows for ANSI escape codes to be called and change the color of text. To do this, you first call echo with the '-e' flag and then for the word or words you want to highlight with a different color. You can see a list of ANSI escape codes and colors here. For my purposes, here's an example of a set of codes I keep is a shared shell library:


RED="\033[31m"
GREEN="\033[32m"
YELLOW="\033[33m"
BLUE="\033[34m"
RESET="\033[0m"


In practice, any time you use an echo -e statement, you can determine if the output you see is normal/expected, if it's an error, if it's a possible warning that doesn't rise to the level of an error, or if you want to display some information that fits some other purpose. Also, once you set a color, that color will remain in place unless you reset back to the default color option.

In practice it looks like this:

if [ $# -lt 5 ] ; then
   echo -e "${RED}Usage: $0 [CUSTOMER] [DUNS] [VERSION] [TEST_TYPE] [filename] ${RESET}"
    exit 1
fi


if [[ "${TEST_TYPE}" = "ZIP" ]] ; then
echo -e "${GREEN}Creating an initial ZIP archive${RESET}"
/c/Program\ Files/7-Zip/7z.exe a -r ./archive-test.zip 001-EmptyFile.txt
fi



Note that the plain text is the output of the command itself, the green text is my own message text to alert me that everything is running as expected or to see if something isn't working how I want to.

For each echo statement or set of statements you want to print out, you can set the color with an escape code, and then you can have that text be formatted as you see fit, anywhere from a single word to an entire line. You do need to end your statement with a RESET code to go back to regular output.

In any event, it's something I've found useful, I figured some of you might, too :).

No comments: