Reputation: 333
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?
Upvotes: 9
Views: 17934
Reputation: 59
These are the colours from tput setaf
1 -> red
2 -> green
3 -> yellow
4 -> blue
5 -> pink
6 -> cyan
7 -> white
Upvotes: 2
Reputation: 531165
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)
Upvotes: 25