0

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
4
  • I would only use this if you are absolutely sure that example.txt cannot contain malicious code: eval echo -e "$line" Commented Aug 8, 2022 at 20:55
  • This works with this example but it won't with my code because in actual txt file are lines that look like this: (@+_let#do/.@#=#>[/]#let=#or@\=<()~if)*<)\). It's not code just string code-styled and I don't want to run it just print it. Commented Aug 8, 2022 at 21:15
  • Do you want to output only one line at a time in your loop or do you want to do more? Commented Aug 8, 2022 at 21:16
  • please update the question to show more sample inputs that are more representative of your real files Commented Aug 8, 2022 at 21:25

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

With bash and envsubst:

export BLUE="\033[0;34m"
export RED="\033[0;31m"
printf "%b\n" "$(envsubst <example.txt)"

See: man envsubst

2 Comments

Works almost perfect! But is there a way to prevent it from escaping characters like \v or \n that may happen in example.txt or do I have to change \v to \\v in example.txt?
@szym See my answer for how to not interpret back-slashes as escape sequences in the example.txt file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.