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"
while IFS= read -r line
do
# print colored line
done < example.txt
It works with hardcoded code in print function but while reading the variable from txt file it doesn't. This works fine:
printf '%b\n' "$BLUE$line"
or this
printf '%b\n' "\033[0;34m$line"
and this
printf '\033[0;34m%s\n' "$line"
but this doesn't:
printf '%b\n' "$line"
# shows ${BLUE} and the rest of the string
# instead of colored output
Is it possible or do I have to change variables in txt file to colors like this:
\033[0;34mSample text
and \033[0;31Sample text.
CodePudding user response:
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 um-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
CodePudding user response:
With bash
and envsubst
:
export BLUE="\033[0;34m"
export RED="\033[0;31m"
printf "%b\n" "$(envsubst <example.txt)"
See: man envsubst