Nabeel Arshad
Nabeel Arshad

Reputation: 487

Send Email on Sql error in crontab centos

I have a MySql script that runs over cron tab in centos linux.

CALL some_stored_procedure();

there is a shell file which calls this MySql script with the name callsqlscript.sh

mysql -uusername -ppassword db_name < /home/scripts/SqlScrip.sql  >> /var/log/SqlscriptsLog.txt

here is my crontab entry

*/1 * * * * root /opt/scripts/callsqlscript.sh 2>&1 | mail -s "SQL Errors" [email protected]

I am getting the emails every minute. I want email to be sent only if there any error running in SQL script.

Is there any way that I get the email only on errors. not every time

Thanks

Upvotes: 0

Views: 65

Answers (1)

Alex Tartan
Alex Tartan

Reputation: 6836

Just use 1> /dev/null

The message of the email is composed of the command's output. If there is none, no mail is sent. The output is comprised of stdout and stderr

So by changing your command to

/opt/scripts/callsqlscript.sh 1> /dev/null 

You redirect stdout to /dev/null (normal output) while keeping stderr (the errors) active. If anything is produced in stderr, that will get emailed to your email address

Upvotes: 1

Related Questions