Home > Blockchain >  Can't print with colors by using environment variables
Can't print with colors by using environment variables

Time:08-30

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?

CodePudding user response:

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.
  • Related