I am trying to print a text in the terminal using echo command.
I want to print the text in a red color. How can I do that?
This question has been answered over and over again :-) but why not.
First using tput
is more portable in modern environments than manually injecting ASCII codes through echo -E
Here's a quick bash function:
say() {
echo "$@" | sed \
-e "s/\(\(@\(red\|green\|yellow\|blue\|magenta\|cyan\|white\|reset\|b\|u\)\)\+\)[[]\{2\}\(.*\)[]]\{2\}/\1\4@reset/g" \
-e "s/@red/$(tput setaf 1)/g" \
-e "s/@green/$(tput setaf 2)/g" \
-e "s/@yellow/$(tput setaf 3)/g" \
-e "s/@blue/$(tput setaf 4)/g" \
-e "s/@magenta/$(tput setaf 5)/g" \
-e "s/@cyan/$(tput setaf 6)/g" \
-e "s/@white/$(tput setaf 7)/g" \
-e "s/@reset/$(tput sgr0)/g" \
-e "s/@b/$(tput bold)/g" \
-e "s/@u/$(tput sgr 0 1)/g"
}
Now you can use:
say @b@green[[Success]]
to get:
tput
First time tput(1)
source code was uploaded in September 1986
tput(1)
has been available in X/Open curses semantics in 1990s (1997 standard has the semantics mentioned below).
So, it's (quite) ubiquitous.