Search code examples
bashunixterminalcolors

How to color terminal output with variable name in another variable


So I want to color my terminal output but nothing works for me. I have script with code and txt file which I read input from. It looks something like this:

example.txt

                                    ${BLUE}_.
                            _/=\:<
                          .#/*${RED}let}
                        //as\@#:~/
                       try()|:-./
                      ${BLUE}*~let${RED}:>${BLUE}@{#
                      </>}#@~*/
                     ${RED}(+!:~/+/
                     /={+|
-

script.sh

BLUE="\033[0;34m"
RED="\033[0;31m"
# print example.txt but colored

Solution

  • Very simply as:

    BLUE=$'\033[0;34m' RED=$'\033[0;31m' envsubst < example.txt
    

    By having the ANSI sequences directly in the environment variables, rather than escape codes, this relieves the need to un-escape the whole file content. ANSI sequences are already encoded.

    Now, a more portable approach would be, to get the actual sequences from tput commands, rather than hard-coded ANSI.

    BLUE=$(tput setaf 4) RED=$(tput setaf 1) envsubst < example.txt