Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch mysql Error in bash

I have a bash script which exports a table from one db and imports it into another. Works like a charm.

However since I want to let it run as a cronjob I would like it to send an email in case for whatever reason I get an error. But how do I find out if I have an error like e.g.:

ERROR 1045 (28000): Access denied for user 'importuser'@'192.168.xxx.xxx' (using password: YES)

Any Idea how to do that? Here is the critical passage:

mysql --user=$rep_user --password=$rep_password --host=$rep_host --database=$rep_name < /tmp/${i}.sql

I already tried

    result=`mysql --user=$rep_user --password=$rep_password --host=$rep_host --database=$rep_name < /tmp/${i}.sql`
    echo $result >> $EMAILMESSAGE

But it doesn't show up in my $EMAILMESSAGE

Has anybody an idea how to achieve this?

like image 666
Calamity Jane Avatar asked Dec 19 '22 08:12

Calamity Jane


1 Answers

I'm assuming your $EMAILMESSAGE variable is already initialised and holds the location of a file. If so, you should be able to get results to it as follows (and only if the command fails):

result=$(mysql --user=$rep_user --password=$rep_password --host=$rep_host --database=$rep_name < /tmp/${i}.sql 2>&1 )
[ $? = 0 ] || echo $result >> $EMAILMESSAGE
like image 135
arco444 Avatar answered Dec 21 '22 23:12

arco444