Bash


cecho – a function to print using different colors in bash

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″]

#!/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


#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’;


Bash: Check if file is found and contains data

The following code will check if the file described by variable FILENAME exists and has data.

if [ ! -f "$FILENAME" ]; then

    echo "Error: '$FILENAME' file not found.";
else

    if [ ! -s "$FILENAME" ]; then

        echo "Error: '$FILENAME' file is empty.";
    else

        echo "Info: '$FILENAME' file found and contains data.";
    fi
fi

Convert a list of integers from MySQL to a Bash array

The following code will connect to a MySQL server, it will get a list of integers and convert the results to a bash array that will be iterated using a for loop and they will be printed using zero padding.


IDS_RAW=$(mysql --user="myuser" --password="mypass" --host="db.example.com" --database="mydb" --batch --compress --skip-column-names --execute="
  SELECT
    Id
  FROM
    Users
  WHERE
    Status = 0;
");

OLDIFS=$IFS;
IFS=$'\n' command eval;
'IDS=($IDS_RAW)';
IFS=$OLDIFS;

echo "Will process the following user IDs '${IDS[@]}'";

for ID in "${IDS[@]}"; do
  LEADING_ZERO=$(printf %08d $ID);
  echo "ID $LEADING_ZERO";
done;

Bash: Get date N days ago in the format YYYY_MM_DD

DEFAULT_DAYS_BACK="0";
DAYS_BACK=${1:-$DEFAULT_DAYS_BACK};
PROCESSING_DATE=`date --date="$DAYS_BACK day ago" +%Y_%m_%d`;

The above code will populate variable PROCESSING_DATE with the date of the day the was DAYS_BACK ago using the format YYYY_MM_DD.

The value for DAYS_BACK is filled by the first argument of the script/function $1. In case the user did not provide an argument, we have the variable DEFAULT_DAYS_BACK that will be used as the default value.