3

I pulled an example from this question to create the following example:

#!/bin/bash
export GREEN='\033[0;32m'
export RED='\033[0;31m'
export NC='\033[0m' # No Color
echo "I ${RED}love${NC} ${GREEN}Stack Overflow${NC}"

It works as expected if I source the file. However, running it as an executable results in the control codes being printed to the screen instead of the colors changing. I presume I need to send some flag to bash to enable the colors, but what?

Elros
  • 273
  • 3
  • 10
  • 1
    taken from your linked question : `if you are using the echo command, be sure to use the -e flag to allow backslash escapes.` – Aserre Apr 27 '18 at 14:35
  • 2
    .. or just use the `printf` to be compliant `printf "I ${RED}love${NC} ${GREEN}Stack Overflow${NC}"` – Inian Apr 27 '18 at 14:36

1 Answers1

8

You don't need export here, and it's simpler to make sure the correct escape character is added to each variable, rather than making echo or printf do the replacement.

GREEN=$'\e[0;32m'
RED=$'\e[0;31m'
NC=$'\e[0m'

echo "I ${RED}love${NC} ${GREEN}Stack Overflow${NC}"

Better yet, use tput to get the correct sequence for your terminal instead of assuming ANSI escape sequences.

GREEN=$(tput setaf 2)
RED=$(tput setaf 1)
NC=$(tput sgr0)
chepner
  • 446,329
  • 63
  • 468
  • 610