Thursday, August 15, 2013

echo colored text in bash

Lots of tutorials tell you to use the "echo -e [blahblah" ANSI escape sequences to generate the colors for output. First of all those are practically impossible to read easily, they look like magic, and its a bitch to try to find a typo.

tput was created a while ago to remedy those issues. I've created a function/script that can be included in other scripts to easily generate colors.
#!/bin/bash
echo_color() {
 case ${1} in
 black)
  shift 1
  #echo $(COLOR)${user-supplied-text}$(NORMAL-COLOR)
  echo $(tput setaf 0)${*}$(tput sgr0)
  ;;
 red)
  shift 1
  echo $(tput setaf 1)${*}$(tput sgr0)
  ;;
 green)
  shift 1
  echo $(tput setaf 2)${*}$(tput sgr0)
  ;;
 yellow)
  shift 1
  echo $(tput setaf 3)${*}$(tput sgr0)
  ;;
 blue)
  shift 1
  echo $(tput setaf 1)${*}$(tput sgr0)
  ;;
 cyan)
  shift 1
  echo $(tput setaf 6)${*}$(tput sgr0)
  ;;
 magenta)
  shift 1
  echo $(tput setaf 5)${*}$(tput sgr0)
  ;;
 white)
  shift 1
  echo $(tput setaf 7)${*}$(tput sgr0)
  ;;
 underline)
  #yes i know its not a color, its still usefull though.
  shift 1
  echo $(tput setaf smul)${*}$(tput sgr0)
  ;;
 custom)
  color_code=${2}
  shift 2
  echo $(tput setaf ${color_code})${*}$(tput sgr0)
  ;;
 ls-color-codes)
  for i in $(seq 0 256); do 
  tput setaf ${i}
  printf " %3s" "$i"
  tput sgr0
  if [ $((($i + 1) % 16)) == 0 ] ; then
   echo #New line
  fi
  done 
  ;;
 *)
  cat <
This script will echo your text as a specified color.

Usage:
 $0
 $0 custom
 $0 ls-color-codes
USAGE
 esac
}
echo_color $*
I'm particularly happy with my ls-color-codes argument, it will print a 16x16 box of the color codes and their colors.

Happy scripting!

No comments:

Post a Comment