Search code examples
bashmacoscolorsecho

echo command color not working


I have a code like this:

#!/bin/bash

COLOR_REST='\e[0m'
COLOR_GREEN='\e[0;32m'
echo -e "${COLOR_GREEN}OK${COLOR_REST}"

When I copy and paste the code into my iTerm, it displays OK in the color of green.

enter image description here

However, when I store the code in a file named testColor.sh, and execute ./testColor.sh. It displays \e[0;32mOK\e[0m on my screen.

Why doesn't it display OK with green?

I've also tried bash testColor.sh, and sh testColor.sh. Both fail to display the text in green.

Another thing I feel strange is that I don't see the -e option in the BSD General Commands Manual in man echo.

I'm using macOS High Sierra as my operating system.


Solution

  • Use

    #!/bin/bash
    
    COLOR_REST="$(tput sgr0)"
    COLOR_GREEN="$(tput setaf 2)"
    printf '%s%s%s\n' $COLOR_GREEN 'OK' $COLOR_REST
    

    which uses printf to avoid echo options and tput to be portable across different terminals.