Shell – How to colorize some of the output of a shell-script

colorsshell-script

I wrote a little Bash script, that uses spfquery for checking upon my domain email SPF record, if it passes on all providers IP addresses:

#!/bin/bash

# RED="\033[1;31m"
GREEN="\033[1;32m"
NOCOLOR="\033[0m"

email="[my email address]" # deleted for bots not to hound me

declare -a ips=("88.86.120.212" "88.86.120.223" "88.86.120.250" "88.86.120.213" "88.86.120.103" "46.234.104.23" "46.234.104.24")

echo -e "\n\n"

for ip in "${ips[@]}"
do
    echo -e "${GREEN}$ip${NOCOLOR}"
    spfquery -sender $email -ip $ip -helo kolbaba.stable.cz
    echo -e "\n\n"
done

Notice, there is RED commented out. That's because I would like the resulting message starting with any of these:

  • fail
  • softfail
  • neutral
  • unknown
  • error
  • none

i.e. not with:

  • pass

to colorize in red.

But how to do this is a mystery to me?

Best Answer

You would want to check the exit code of spfquery, then have an if/else to see if it was a pass or not. Something like this:

#!/bin/bash

RED="\033[1;31m"
GREEN="\033[1;32m"
NOCOLOR="\033[0m"

email="info@vlastimilburian.cz"

declare -a ips=("88.86.120.212" "88.86.120.223" "88.86.120.250" "88.86.120.213" "88.86.120.103" "46.234.104.23" "46.234.104.24")

echo -e "\n\n"

for ip in "${ips[@]}"
do
    spfquery -sender $email -ip $ip -helo kolbaba.stable.cz

    exit_status=$?
    if [ $exit_status -eq 0 ]; then
        echo -e "${GREEN}$ip${NOCOLOR}"
    else
        echo -e "${RED}$ip${NOCOLOR}"
    fi

    echo -e "\n\n"
done