To print colored words, I could do this in shell:
declare -A COLORS
COLORS["red"]='\033[0;31m'
COLORS["default"]='\033[0m'
echo -e "${COLORS["red"]}abc${COLORS["default"]}" # With color
echo -e "xyz" # No color.
echo -e "${COLORS["red"]}lmn${COLORS["default"]}" # With color
But copy+pasting the lines with the color is hard to maintain when the debug messages that need color are everywhere.
I've tried to put it in a function as such:
function RedPrint () {
echo -e "${COLORS["red"]}$1${COLORS["default"]}" >&2
}
The nice thing is the RedPrint allows global variable:
G="hahaha"
RedPrint "abc $G foo bar"
RedText "blah blah "${G}" foo foo bar"
But I'm sure there are some caveats that I haven't encountered. Would the functionalized RedPrint
behave the same as how I would use echo -e
?
The question (in parts) is:
- Is there an easier way to manipulate colors in shell? Are there alternatives?
- Is the function with
echo
a good way to maintain the color prints? How else canRedPrint
be written?