Cron-Jobs

Writing Emails from Cron-Job

In the crontab the script is called every 5 minutes, and with the MAILTO variable its defined where the email is sent to:
MAILTO="firstname@domain.com,secondname@domain.com"
*/5 * * * * /home/user/Projects/scripts/check_every_5_minutes.sh
We send the mail inside the script, since we can control the email subject and we have a differentiation between a regular message (with our own subject) and an script error (where the script name is in the email subject):
#!/bin/bash -ue

OUT=/tmp/$(basename $0).log
# Using $MAILTO environment variable from cronjob
EMAIL=${MAILTO:-}

if [...] ; then
    echo "test" >> $OUT
fi

set +u
if [ -n "$EMAIL" ] ; then
    # send email by 'mail' command to be able to set an subject
    cat $OUT | mail -s "Jenkins Mount Error" $EMAIL
else
    # write output directly - e.g. when not called by crontab
    cat $OUT
fi
rm -f $OUT

Limiting Email Sending

Sometimes we want to check every 5 minutes whether the state is correct, but then don't want to receive the error message that frequent:
#!/bin/bash -ue

# Print error message every hour
INT_S=360

STAMP=/tmp/$(basename $0).timestamp
NOW_S=$(date +%s)
LST_S=$(test -e $STAMP && cat $STAMP || echo $(($NOW_S-$INT_S)))
DFF_S=$(($NOW_S-$LST_S))


if [...] ; then
    echo "test" >> $OUT
fi

if [ $DFF_S -ge $INT_S ] ; then
    set +u
    if [ -z "$EMAIL" ] ; then
        cat $OUT
    else
        cat $OUT | mail -s "Jenkins Mount Error" $EMAIL
    fi
fi