Escape characters in a variable

Debian 9 64x - LXDE

How can i disable escape sequences in a variable?

#!/bin/bash
#mainscript
  . "./links.bash"
  echo "$red_start This text should be red $color_end"
#!/bin/bash
#links.bash
  #colors
  red_start="\e[91m"
  color_end="\e[0m"

Output that i get:
\e[91m This text should be red \e[0m

Output expected:
This text should be red <- RED

Please make it a habit to post your system's info in every single new thread, as you did thankworthily in your very first post in here: "Debian 9 64x - LXDE".

As for your problem: the bash builtin echo needs the -e option. man bash :

Same holds true for the external /bin/echo comand on linux systems. It does not necessarily on other systems.

echo "$red_start This text should be red $color_end"
\e[91m This text should be red \e[0m
echo -e "$red_start This text should be red $color_end"
 This text should be red 
1 Like

Thank you very much. This solved the problem!:slight_smile:

Alternative, more standard way:

printf "${red_start}%s${color_end}\n" "This text should be red"

or

redtext="${red_start}%s${color_end}"
printf "${redtext}\n" "This text should be red"

Also another method for echo without the -e option:
(AND, using the POSIX only dash as the shell too.)

Last login: Sun Mar 31 10:12:31 on ttys000
AMIGA:amiga~> dash
AMIGA:\u\w> ESC=$( printf "\033" )
AMIGA:\u\w> /bin/echo "$ESC[32;45mThis is coloured text.$ESC[0m"
This is coloured text.
AMIGA:\u\w> exit
AMIGA:amiga~> _

See snapshot...

This works but one can enter the ESC character (and most other characters) directly, at least in vi *) so you won't need a subshell: in insert mode press <CTRL>-<V> to enter the next character verbatim. If you press i.e. <CTRL>-<V> and then <ESC> the editor window will show usually this:

^[
~
~
~

This is vi s way of "printing" an unprintable character. Moving over with the cursor will confirm that it is NOT a caret character followed by a opening square bracket but a single character - the ESC. You can use it exactly as this. I usually put a comment on such lines to make sure i remember that:

typeset chMyESC="^["           # WARNING: literal ESC char!

Likewise you can i.e. enter literal <ENTER> characters the same way which will look like ^M and may more.

I hope this helps.

bakunin
__________
*) i have heard rumors about other editors being out there too. They haven't been confirmed yet.