Linux - Display text in different colors on the terminal

By xngo on June 30, 2019

In Linux, in order to display text in different colors on the terminal, you have to use the tput command. It has the ability to set the background and foreground color of text. You have to use the following command options:

  • tput setaf : Set foreground color.
  • tput setab : Set background color.

However the number of colors available is limited. The command tput colors shows the number of colors available. On my system, it is 256.

Below is a Bash function example that will print the number in green if it is position and red if it is negative.

set -e
  local LABEL=$1
  local VALUE=$2
  local COLOR_CODE=""
  if [ "${VALUE}" -lt 0 ]; then
    COLOR_CODE=$(tput setaf 1) # red color.
    COLOR_CODE=$(tput setaf 2) # green color.
  local RESET_COLOR=$(tput sgr0)
  printf "%22s: ${COLOR_CODE}%'6d${RESET_COLOR}\n" "${LABEL}" "${VALUE}"


Screenshot showing numbers in different color on the terminal



About the author

Xuan Ngo is the founder of He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.