Catching exit code after executing mysql query

12,775

You are in the good way: $? is the flag to check:

$ mysql -h mydb <<< "SELECT * FROM MyDB.some_table_that_exists;"
$ echo $?
0

$ mysql -h mydb <<< "SELECT * FROM MyDB.asdfasdfasdf;"
ERROR 1146 (42S02) at line 1: Table 'MyDB.asdfasdfasdf;' doesn't exist
$ echo $?
1

So what you can do is to execute the query and then:

if [ $? ... ]; then ...
Share:
12,775
andresg3
Author by

andresg3

Updated on June 04, 2022

Comments

  • andresg3
    andresg3 almost 2 years

    I'm working on a bash script that will query mysql. I would like to add some error checking. Let say if the following query for some reason fails I want to catch the exit error and exit the script. For example this is part of my script.

    QUERY="SELECT DISTINCT `TABLE_SCHEMA`, `TABLE_NAME`
    FROM `information_schema`.`TABLES`
    WHERE  table_schema NOT IN ( 'mysql', 'information_schema', 'performance_schema' )"    
    
    mysql -u user -pPASSWD --batch -N -e "$QUERY" | while read DATABASE TABLE;
    do
      ...
      ...
      ...
    done
    

    How could i catch the exit code after the scripts run the "$QUERY". I was thinking something like this. But it doesn't seem to work.

    mysql -u user -pPASSWD --batch -N -e "$QUERY" echo $? | while read DATABASE TABLE;
    

    Any ideas