How to echo colored text in linux shell script

Try following command on you bash:
bash $] tput setaf 1
You will see your text color will turn red.
To reset it you can type following command to make text color white
bash $] tput setaf 7

or to reset everything again text modes
bash $] tput sgr0

Same things you can use in your bash script to colorize output.

Consider following sample bash script for colorize echo:

[ad#ad-2-468-x-60]
#try.sh
txtrst=$(tput sgr0) # Text reset
txtred=$(tput setaf 1) # Red
echo “Welcome to ${txtred} kedar.nitty-witty.com ${txtrst}!”

Output::

colored-shell-script

Other variables you can define as follows:
txtgrn=$(tput setaf 2) # Green
txtylw=$(tput setaf 3) # Yellow
txtblu=$(tput setaf 4) # Blue
txtpur=$(tput setaf 5) # Purple
txtcyn=$(tput setaf 6) # Cyan
txtwht=$(tput setaf 7) # White
txtrst=$(tput sgr0) # Text reset
Following are the tput details further:
tput setab [1-7] : Set a background colour using ANSI escape
tput setb [1-7] : Set a background colour
tput setaf [1-7] : Set a foreground colour using ANSI escape
tput setf [1-7] : Set a foreground colour

tput Text Mode Capabilities:

tput bold : Set bold mode
tput dim : turn on half-bright mode
tput smul : begin underline mode
tput rmul : exit underline mode
tput rev : Turn on reverse mode
tput smso : Enter standout mode (bold on rxvt)
tput rmso : Exit standout mode
tput sgr0 : Turn off all attributes (doesn’t work quite as expected)


You might also like::

  1. Simple Shell Script to Monitoring Disk Space on a Linux Machine
  2. Linux Shell Commands – quick how-tos
  3. Using VLookup like Batch script to compare two excel / csv