Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I need to automate the mysql script execution in linux. If one sql script fails, it should not proceed further. It should come out of the script. I am using ${?} to test the exit status. But it's always returning the zero status though script has failed. I think it's returning zero because mysql command executed successfully even though script has failed with valid error. Please help me with the same. Also I want to know how to rollback if any script failed with valid error. Please check my code as below

#!/bin/bash
# Load the script and env configuration
. /home/base/scripts/conf/sql.conf
if ls ${HOME_PATH}/sql_actual/*.sql &> /dev/null; then
   for file in ${HOME_PATH}/sql_actual/*.sql
   do
       echo ${file}
       s=${file##*/}
       var_log=${s%.sql}
       echo ${var_log}
     mysql -u ${DB_USER} -p${DB_PASSWORD} -h ${DB_HOST} --default-character-set=utf8 ${DB_SCHEMA} < $file --silent --force -b 2>${HOME_PATH}/sql-logs/${var_log}.log
         if [ ${?} -ne 0 ]; then
        echo "${var_log}.sql SQL Script Failed to execute"
        exit ${?}
        else
        echo -e "${var_log}.sql" SQL Script executed successfully
        fi
done
else
    echo "files do not exist"
fi
share|improve this question
    
What is your MySQL version? Does it still return 0 as the exit code after failure if you are not using the --force option? –  Josh Jolly yesterday
    
mysql version is Server version: 5.5.30 MySQL Community Server (GPL) by Remi –  user1041177 yesterday
1  
Because of the backticks, you are capturing exit code, of command that mysql printed to stdout. If mysql not printed anything, you have 0, because no command can not return any error. –  iokanuon yesterday

1 Answer 1

mysql -u ${DB_USER} -p${DB_PASSWORD} -h ${DB_HOST} --default-character-set=utf8 ${DB_SCHEMA} < $file --silent --force -b 2>${HOME_PATH}/sql-logs/${var_log}.log

exitcode=$?

if [ $exitcode -ne 0 ]; then
share|improve this answer
    
I tried this . I assigned the $? to variable called RC and executed the script, but its returning status code as zero though script has failed. Please check the line + RC=0 + '[' 0 -ne 0 ']' –  user1041177 yesterday
    
Are the backticks really necsesary? –  iokanuon 23 hours ago
    
Its not necessary. I reomved the backticks and tried . But still iam getting the same issue –  user1041177 11 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.