How to catch mysql Error in bash

10,394

Solution 1

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

Solution 2

mysql works like any other unix command line tool, you can use the exit status of the command.

So you can use it in if, use short-circuiting || or &&, or directly check $?.

Share:
10,394
Calamity Jane
Author by

Calamity Jane

PHP Developer in Germany I guess I can call myself a senior by now.

Updated on June 04, 2022

Comments

  • Calamity Jane
    Calamity Jane almost 2 years

    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?