Search code examples
linuxbashshellredhatraspbian

On Linux, why can't 'echo' use ANSI color codes but 'print' could?


As practice, I made a shell script that outputs a colored message on the screen. I was trying to use ANSI color codes but the content itself would output instead.

My code:

#!/bin/bash
echo "\033[1;37;42m SUCCESS! \033[0m"

Output:

\033[1;37;42m SUCCESS! \033[0m

However, using 'print' does work:

#!/bin/bash
print "\033[1;37;42m SUCCESS! \033[0m \n"

Output (with white font + green background):

SUCCESS!

I tested this on Red Hat Enterprise Linux Server release 6.5 (Santiago) and Raspbian Jessie Lite 4.4, and had the same results. To the best of my knowledge and from all the search engine results I've gone through, 'echo' and 'print' are the same except 'echo' includes a newline and 'print' does not. Why in this case would it be different?


Solution

  • By default, echo will interpret it as a string, literally. You have to tell echo to interpret backslashes appropriately.

    From the documentation:

    -e enable interpretation of backslash escapes

    echo -e "\033[1;37;42m SUCCESS! \033[0m"