Linux Shell脚本在执行mysql脚本shell后捕获退出代码

时间:2014-08-05 09:42:09

标签: mysql linux bash shell

我需要在linux中自动执行mysql脚本。如果一个sql脚本失败,则不应继续进行。它应该出自脚本。我使用$ {?}来测试退出状态。但是,尽管脚本失败,它总是返回零状态。我认为它返回零,因为即使脚本因有效错误而失败,mysql命令也会成功执行。请帮我一样。此外,我想知道如果任何脚本失败并返回有效错误,如何回滚。请检查我的代码如下

#!/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

1 个答案:

答案 0 :(得分:2)

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