Feb 102014
 

An old article by Todd Partridge (Gently) but still really useful if you are writing some bash scripts and want them more readable with some colors:

Users who have been using Linux for awhile often learn that creating a basic script is a good way to run multiple, often-repeated commands. Adding a little color to scripts can additionally provide nice feedback. This can be done in a fairly straight-forward way by using the tput command.




A common way of doing this is to define the colors that tput can produce by putting them at the beginning of the bash script:

#!/bin/bash
# scriptname - description of script
 
# Text color variables
txtund=$(tput sgr 0 1)          # Underline
txtbld=$(tput bold)             # Bold
bldred=${txtbld}$(tput setaf 1) #  red
bldblu=${txtbld}$(tput setaf 4) #  blue
bldwht=${txtbld}$(tput setaf 7) #  white
txtrst=$(tput sgr0)             # Reset
info=${bldwht}*${txtrst}        # Feedback
pass=${bldblu}*${txtrst}
warn=${bldred}*${txtrst}
ques=${bldblu}?${txtrst}

When writing new scripts using templates with these variables already defined can quicken the creation process and help keep scripts organized

If just needing to use tput colors for specific instances this script can display the tput definitions and their corresponding possibilities:

#!/bin/bash
# tputcolors
 
echo
echo -e "$(tput bold) reg  bld  und   tput-command-colors$(tput sgr0)"
 
for i in $(seq 1 7); do
  echo " $(tput setaf $i)Text$(tput sgr0) $(tput bold)$(tput setaf $i)Text$(tput sgr0) $(tput sgr 0 1)$(tput setaf $i)Text$(tput sgr0)  \$(tput setaf $i)"
done
 
echo ' Bold            $(tput bold)'
echo ' Underline       $(tput sgr 0 1)'
echo ' Reset           $(tput sgr0)'
echo

You should get an output similar to this one:

tputcolors

Popular Posts:

Flattr this!

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)

*