Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can't print with colors by using environment variables

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

\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?

>Solution :

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.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading