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?
A neat way to change color only for one echo
is to define such function:
function coloredEcho(){
local exp=$1;
local color=$2;
if ! [[ $color =~ '^[0-9]$' ]] ; then
case $(echo $color | tr '[:upper:]' '[:lower:]') in
black) color=0 ;;
red) color=1 ;;
green) color=2 ;;
yellow) color=3 ;;
blue) color=4 ;;
magenta) color=5 ;;
cyan) color=6 ;;
white|*) color=7 ;; # white or invalid color
esac
fi
tput setaf $color;
echo $exp;
tput sgr0;
}
Usage:
coloredEcho "This text is green" green
Or you could directly use color codes mentioned in Drew's answer:
coloredEcho "This text is green" 2