Catching exit code after executing mysql query
bash, batch-file, error-handling, mysql, shell
Solution
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 ...
Problem
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