How to echo colored text in linux shell script

Having a colourful display on shell script is something that’d beautify your experience. Using colour text and echos will help you to highlight and distinguish the shell output on a linux prompt.

Here’s how you can have colored text in linux shell, try following command on your 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.

Create following sample bash script for colourize echo:

# vi try.sh 
#ColourfulText
txtrst=$(tput sgr0) # Text reset
txtred=$(tput setaf 1) # Red
echo "Welcome to ${txtred} kedar.nitty-witty.com ${txtrst}!"

The coloured text output is as follows::

If you need more colors, you may define them as follows in 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)

I hope you liked this. Happy & colourful shell scripting.  🙂

Exit mobile version