1

I have a .echo_colors file containing some variables for colors in the following format:

export red="\033[0;31m"

this works fine with echo -e, but i want to use this environment variables on a C code. I'm getting the variable via getenv and printing with printf:

#include <stdlib.h>
#include <stdio.h>

int main(){
    char* color = getenv("red");
    printf("%s", color);
    printf("THIS SHOULD BE IN RED\n");
    return 0;
}

with this program, i get

\033[0;31mTHIS SHOULD BE IN RED

The string is just being printed and not interpreted as a color code. printf("\033[0;31m") works and prints output in red as i want to. Any ideas for what to do to correct this problem?

Guiusa
  • 21
  • 4
  • Why not simply create a header file, say `ansicolor.h` and within it (properly guarded) `#define RED "\033[0;31m"` (and the rest) and `#define NC "\033[0m"` (for no color) to return to normal? Then rather than querying the environment and worrying about shell syntax, you simply include the C header?? – David C. Rankin Sep 03 '22 at 01:46

2 Answers2

2

Bash doesn't interpret \033 as "ESC" by default, as evident from hex-dumping the variable, but as "backslash, zero, three, three":

bash-3.2$ export red="\033[0;31m"
bash-3.2$ echo $red | xxd
00000000: 5c30 3333 5b30 3b33 316d 0a              \033[0;31m.

You'll need to use a different Bash syntax to export the variable to have it interpret the escape sequence (instead of echo -e doing it):

export red=$'\033[0;31m'

i.e.

bash-3.2$ export red=$'\033[0;31m'
bash-3.2$ echo $red | xxd
00000000: 1b5b 303b 3331 6d0a                      .[0;31m.
AKX
  • 152,115
  • 15
  • 115
  • 172
  • This works. I thought the problem was probably bash syntax but still didnt't know how to fix this. Thank you very much – Guiusa Aug 29 '22 at 13:47
  • 2
    Also, avoid using `echo -e` if at all possible --`echo` options are a hopelessly inconsistent mess. See ["Strange behaviour for `echo` with `-e` flag passed to bash with `-c` flag"](https://stackoverflow.com/questions/51101308/strange-behaviour-for-echo-with-e-flag-passed-to-bash-with-c-flag), ["Escape sequences with `echo -e` in different shells"](https://unix.stackexchange.com/questions/88307/escape-sequences-with-echo-e-in-different-shells), and ["Why is `printf` better than `echo`?"](https://unix.stackexchange.com/questions/65803/why-is-printf-better-than-echo). – Gordon Davisson Aug 29 '22 at 18:21
0

Use ^[ (Control-left-bracket) in your shell script to key in the export command, as in

$ export red="<ctrl-[>[0;31m"

in your shell script, the ctrl-[ is actually the escape character (as typed from the terminal, it is possible that you need to escape it with Ctrl-V so it is not interpreted as an editing character, in that case, put a Ctrl-V in front of the escape char)

If you do

$ echo "<ctrl-[>[31mTHIS SHOULD BE IN RED"
THIS SHOULD BE IN RED                   (in red letters)
$ _

you will see the effect.

Luis Colorado
  • 10,974
  • 1
  • 16
  • 31