1

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 can RedPrint be written?
alvas
  • 115,346
  • 109
  • 446
  • 738

1 Answers1

2

There is no other main way to output colored text as far as I know.

The only other possible alternative would be to use tput to generate the color codes, as tput will take into account your current terminal's capabilities before outputting values (better for cross-environment).

For example you would do:

declare -A COLORS
COLORS["red"]=$(tput setaf 1)
COLORS["default"]=$(tput setaf 9)

Where:

Value | Color
-------------
0     | Black
1     | Red
2     | Green
3     | Yellow
4     | Blue
5     | Magenta
6     | Cyan
7     | White
8     | Unused
9     | Default

As for your function, you should have no problem as long as you are okay printing the entire line the same color and as long as the string that you pass to it doesn't have multiple colors itself.

gregnr
  • 1,222
  • 8
  • 11