Skip to content

Instantly share code, notes, and snippets.

@peter-bloomfield
Last active April 27, 2020 11:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peter-bloomfield/fa3c2da60cb1ec5d1630ac83ae01917d to your computer and use it in GitHub Desktop.
Save peter-bloomfield/fa3c2da60cb1ec5d1630ac83ae01917d to your computer and use it in GitHub Desktop.
A bash function to echo coloured log messages.
#!/usr/bin/env bash
# Function echo text to the screen.
# There are two ways to invoke this:
#
# print LEVEL MESSAGE
# print MESSAGE
#
# In the first case, LEVEL can be one of: DEBUG, INFO, SUCCESS, WARNING, or ERROR.
# This determines the colour used to display the message. If the level is not recognised then it defaults to INFO.
# In the second case, the message is displayed as though LEVEL was set to INFO.
function print
{
# If there are two arguments then the first is LEVEL and the second is MESSAGE.
# If there is only one argument then it is the message. LEVEL defaults to INFO.
local level="${1:-}"
local message="${2:-}"
if [[ "${message}" = "" ]]; then
message="${1:-}"
level="INFO"
fi
local format="\e[0m"
local resetFormat="\e[0m"
local prefix=""
# Pick a suitable display colour.
case "${level}" in
"DEBUG" )
# Dim text
format="\e[2m"
prefix="[ DEBUG ]: "
;;
"INFO" )
# Default text format.
prefix="[ INFO ]: "
;;
"SUCCESS" )
# Green text.
format="\e[32m"
prefix="[SUCCESS]: "
;;
"WARNING" )
# Yellow text.
format="\e[33m"
prefix="[WARNING]: "
;;
"ERROR" )
# Bold/bright red text.
format="\e[1;31m"
prefix="[ ERROR ]: "
;;
* )
# Use default format.
prefix="[${level}]: "
;;
esac
echo -e "${resetFormat}${format}${prefix}${message}${resetFormat}"
}
@peter-bloomfield
Copy link
Author

Example usage:

print DEBUG "This is a debugging message."
print INFO "This message provides general status information."
print SUCCESS "This message indicates that something has succeeded."
print WARNING "Something concerning has happened."
print ERROR "Something really bad has happened."

print "Messages default to INFO if no level is provided."
print CUSTOM_LEVEL "This message has a custom level tag. It uses INFO formatting though."

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment