Bash – Output Colored Text Without Non-Word Color Codes

bashcolorsdistributionsoutputstability

I found these ways, for example, to output colored text in a simple way to the screen:

RED="\033[0;31m" # Red color (via ANSI escape code);
NC='\033[0m' # No color (via ANSI escape code);
echo -e "${RED}This text is red. ${NC}" # -e flag allows backslash escapes;

or:

printf '\e[1;34m%-6s\e[m' "This is blue text"

I also found:

tput setaf 1; echo "this is red text"

But I never used tput and I'm not sure it's shipped with all major distros (Debian, CetnOS, Arch, and so forth).

My question

How to output colored text in a given named, common color (like "Red") in a simple way I could count on to work on all major distros, without using "messy" color codes?

Best Answer

Codes (ANSI colour codes)

The codes are not distro dependent. They are terminal dependent. Some terminals will not support them. However they are probably supported by most.

Names

Use variables to give names e.g.

red="$(tput setaf 1)"
echo "${red}hello"

note: don't use capitals for shell variables, capitals should be reserved for environment variables.

Names and codes

The codes refer to a colour number. the colour for each number is defined by the terminal, and in non-standard. The user can change it.

Related Question