3

I have a cron job that runs a script.sh file (Which takes the backup of DB), and sends me an email every hour. In script.sh file, I'm taking backup of few databases(.sql file), then creating .zip of that. My issue is, I want to get an email only if something goes wrong. Currently I'm getting the following Email every hour.

adding: db2017_173601.sql (deflated 89%)
adding: bvDatabase_173601.sql (deflated 94%)
adding: cmc_173601.sql (deflated 60%)

Any idea how to solve this? I'm using this code in my crontab:(-E option to prevent empty body in heirloom mailx)

/60 * * * *  /usr/local/sbin/mysqldata.sh 2>&1 | mail -s "Backup Failed" -E email@example.com
Ash
  • 97

1 Answers1

2

I think you need to do in two steps:

  1. Save the output and errors to a log file
  2. If the script exited with non-zero, then send the log file by email

For example:

/60 * * * *  /usr/local/sbin/mysqldata.sh >/path/to/log 2>&1; [ $? != 0 ] && mail -s "Backup Failed" -E email@example.com < /path/to/log
janos
  • 3,505