I am trying to print a text in the terminal using echo command.
I want to print the text in a red color. How can I do that?
This is the color switch \033[. See history.
Color codes are like 1;32 (Light Green), 0;34 (Blue), 1;34 (Light Blue), etc.
We terminate color sequences with a color switch \033[ and 0m, the no-color code. Just like opening and closing tabs in a markup language.
SWITCH="\033["
NORMAL="${SWITCH}0m"
YELLOW="${SWITCH}1;33m"
echo "${YELLOW}hello, yellow${NORMAL}"
Simple color echo function solution:
cecho() {
local code="\033["
case "$1" in
black | bk) color="${code}0;30m";;
red | r) color="${code}1;31m";;
green | g) color="${code}1;32m";;
yellow | y) color="${code}1;33m";;
blue | b) color="${code}1;34m";;
purple | p) color="${code}1;35m";;
cyan | c) color="${code}1;36m";;
gray | gr) color="${code}0;37m";;
*) local text="$1"
esac
[ -z "$text" ] && local text="$color$2${code}0m"
echo "$text"
}
cecho "Normal"
cecho y "Yellow!"