Saturday, 16 July 2011

Bash script to automate report checking

The script below is a convenient hack to automate manual report checking. It requires uuencode and mailx (or equivalents) to be installed and uses the regular expression provided on the command line to check if the occurrences are greater than the specified number. This allows for a number of convenient checks:

  • Using "$" as the regex and a count of 1 prevents empty reports from being sent. The count can be changed to 2 if the report has a header line even when it has no results.
  • A specific condition can be matched, for example using a regex of "Match this text" to email the report only if the text appears in the report.

As always, there are multiple ways of solving the problem. This was a quick an convenient script to allow multiple reports to be checked and mailed to different recipients under different conditions.

#!/bin/bash
# Shell script for checking a named (text) report for a number of occurrences of a
# search if the search string is found at least the number of times specified then
# the report is mailed to the specified email list
#
# Usage example:
# This command will check the report.csv report for any entries ($REPORT_DIR needs
# to be set):
# ./check_report.sh report.csv "$" 1 my.email@address "Email Subject"

cd $REPORT_DIR

if [ -e $1 ]; then
    COUNT=`grep -c "$2" "$1"`
    if [ $COUNT -gt $3 ]; then
        uuencode "$1" "$1" | mailx -s "Check Report $5" "$4" > /dev/null
    fi
fi