Pipable command to print in color?
I don't know of any utility for colored printing itself, but you can do it easily with a shell function like this:
# colorize stdin according to parameter passed (GREEN, CYAN, BLUE, YELLOW)
colorize(){
GREEN="\033[0;32m"
CYAN="\033[0;36m"
GRAY="\033[0;37m"
BLUE="\033[0;34m"
YELLOW="\033[0;33m"
NORMAL="\033[m"
color=\$${1:-NORMAL}
# activate color passed as argument
echo -ne "`eval echo ${color}`"
# read stdin (pipe) and print from it:
cat
# Note: if instead of reading from the pipe, you wanted to print
# the additional parameters of the function, you could do:
# shift; echo $*
# back to normal (no color)
echo -ne "${NORMAL}"
}
echo hi | colorize GREEN
If you want to check other colors, take a look at this list. You can add support for any color from there, simply creating an additional variable at this function with the correct name and value.
I created this function that I use in bash scripts.
# Function to echo in specified color echoincolor () { case $1 in "red") tput setaf 1;; "green") tput setaf 2;; "orange") tput setaf 3;; "blue") tput setaf 4;; "purple") tput setaf 5;; "cyan") tput setaf 6;; "gray" | "grey") tput setaf 7;; "white") tput setaf 8;; esac echo "$2"; tput sgr0 }
Then I just call it like this echoincolor green "This text is in green!"
Alternatively, use printf
# Function to print in specified color colorprintf () { case $1 in "red") tput setaf 1;; "green") tput setaf 2;; "orange") tput setaf 3;; "blue") tput setaf 4;; "purple") tput setaf 5;; "cyan") tput setaf 6;; "gray" | "grey") tput setaf 7;; "white") tput setaf 8;; esac printf "$2"; tput sgr0 }
Then just call it like this colorprintf green "This text is in green!"
Note, echo
provides a trailing new line while printf
does not.