The following script can be used to print colored text in bash
.
You can use it in any script without copy pasting everything in it by executing the following command source cecho.sh
.
Doing so, it will load to your script the functions that are defined in cecho.sh
, making them available for you to use (something like including code in C, with some caveats).
[download id=”2113″]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | #!/bin/bash # The following function prints a text using custom color # -c or --color define the color for the print. See the array colors for the available options. # -n or --noline directs the system not to print a new line after the content. # Last argument is the message to be printed. cecho () { declare -A colors; colors=(\ [ 'black' ]= '\E[0;47m' \ [ 'red' ]= '\E[0;31m' \ [ 'green' ]= '\E[0;32m' \ [ 'yellow' ]= '\E[0;33m' \ [ 'blue' ]= '\E[0;34m' \ [ 'magenta' ]= '\E[0;35m' \ [ 'cyan' ]= '\E[0;36m' \ [ 'white' ]= '\E[0;37m' \ ); local defaultMSG= "No message passed." ; local defaultColor= "black" ; local defaultNewLine= true ; while [[ $ # -gt 1 ]]; do key= "$1" ; case $key in -c|--color) color= "$2" ; shift ; ;; -n|--noline) newLine= false ; ;; *) # unknown option ;; esac shift ; done message=${1:-$defaultMSG}; # Defaults to default message. color=${color:-$defaultColor}; # Defaults to default color, if not specified. newLine=${newLine:-$defaultNewLine}; echo -en "${colors[$color]}" ; echo -en "$message" ; if [ "$newLine" = true ] ; then echo ; fi tput sgr0; # Reset text attributes to normal without clearing screen. return ; } warning () { cecho -c 'yellow' "$@" ; } error () { cecho -c 'red' "$@" ; } information () { cecho -c 'blue' "$@" ; } |
Usage
Function cecho
accepts the options to set the color and to control if a new line should be print.
Parameter -c
or --color
define the color for the print. See the array colors
for the available options.
Parameter -n
or --noline
directs the system not to print a new line after the content.
The last parameter is the string message to be printed.
Functions warning
, error
and information
are using cecho
to print in color.
These three functions always print a new line and they have hardcoded one color set for each.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #Get the name of the script currently being executed scriptName=$( basename $( test -L "$0" && readlink "$0" || echo "$0" )); #Get the directory where the script currently being executed resides scriptDirDIR=$( cd $( dirname "$0" ) && pwd ); #Print in blue color with no new line cecho -n -c 'blue' "$scriptDir" ; #Print in red color with a new line following the message cecho -c 'red' "$scriptName" ; #Using the information() function to print in blue followed by a new line information ‘End of script’; |
This post is also available in: Greek