1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
|
#!/bin/bash
#
# Copyright (C) 2012-2020 SUSE Software Solutions Germany GmbH
#
# Author:
# Frank Sundermeyer <fsundermeyer at opensuse dot org>
#
#
function print_help {
cat <<EOF_helptext
Conditional Color echo
Usage: ccecho "LEVEL" "MESSAGE"
Prints a colored message string to STDOUT or STDERR using bash color codes. The
color and the output channel depend on the LEVEL keyword. When the SHELL
environment variable COLOR is set to either "0" or "no" no color output is
generated.
The main purpose of this script is to provide an easy method to generate
colored output when the output should go to STDOUT, and regular output
(with no color codes messing up the output) for log files, pipes and
scripts (by exporting COLOR=0)
LEVEL keywords
normal -> no color, STDOUT
error -> bold red, STDERR
info -> purple, STDOUT
result -> green, STDOUT
warn -> red, STDERR
MESSAGE
The message to be printed. Needs to be quoted using double quotes.
You may use sequences supported by echo (1) such as \n to insert a
newline and \t to insert a tab.
EOF_helptext
}
#----------------------------------------------------------------------
# printing help / catching errors
#
ME=$(basename "$0")
ARGS=$(getopt -o h -l help -n "$ME" -- "$@")
eval set -- "$ARGS"
while true ; do
case "$1" in
-h|--help)
print_help
exit
shift
;;
--)
shift
break
;;
esac
done
if [[ -z "$1" || -z "$2" ]]; then
echo "ERROR: $ME must be called with two parameters:
LEVEL and MESSAGE
See '$ME -h' or 'man 1 $ME' for more information" >&2
exit 1
fi
#----------------------------------------------------------------------
# MAIN
#
LEVEL="$1"
MESSAGE="$2"
START_COLOR=""
END_COLOR=""
# set colors according to level if colored output is wanted
#
if [[ 0 != "$COLOR" && no != "$COLOR" ]]; then
END_COLOR="\e[0m"
if [[ error = "$LEVEL" ]]; then
START_COLOR="\e[1;31m"
elif [[ info = "$LEVEL" ]]; then
START_COLOR="\e[35m"
elif [[ result = "$LEVEL" ]]; then
START_COLOR="\e[32m"
elif [[ warn = "$LEVEL" ]]; then
START_COLOR="\e[31m"
fi
# in case you do a tail or a head on the output, the last/first color code
# might get cut, leading to unwanted results
# To be on the safe side, we make sure every line that is printed starts
# and ends with a color code
# (\ from \n needs to be escaped)
#
MESSAGE=${MESSAGE//\\n/${END_COLOR}\\n${START_COLOR}}
fi
if [[ error = "$LEVEL" || warn = "$LEVEL" ]]; then
echo -e "${START_COLOR}${MESSAGE}${END_COLOR}" >&2
else
echo -e "${START_COLOR}${MESSAGE}${END_COLOR}"
fi
|