【问题标题】:Catch Mysql Error in bash在 bash 中捕获 Mysql 错误
【发布时间】:2015-10-09 20:12:59
【问题描述】:

我有一个查询 mysql 的 bash 脚本,我想捕捉错误并回显它。这是我的代码

 mysql --silent -h ${sql_server} -P 3306 -u${USER} -p${MYSQL_PASS} -D${DATABASE} -BNe "$sql_str" | while read -r line
do
    query="$(echo "$line" | cut -f1)"
    database_out="$(echo "$line" | cut -f2)"
    outfile="$(echo "$line" | cut -f3)"
    directory_out="$(echo "$line" | cut -f4)"
    type="$(echo "$line" | cut -f5)"
    host="$(echo "$line" | cut -f6)"
    username="$(echo "$line" | cut -f7)"
    directory_scp="$(echo "$line" | cut -f8)"

    #switch over format types
    case "$type" in 
        csv)
            file_out=$directory_out$outfile"."`date +%Y%m%d`.csv
            mysql -h ${sql_server} -P 3306 -u${USER} -p${MYSQL_PASS} -D${database_out} -e "$query" | sed 's/\t/","/g;s/^/"/;s/$/"/;s/\n//g' > $file_out
            ;;
        xml)
            file_out=$directory_out$outfile`date +%Y%m%d`.xml
            mysql -h ${sql_server} -P 3306 -u${USER} -p${MYSQL_PASS} -D${database_out} -e "$query" -X > $file_out
            ;;
        *)
        echo "["$(timestamp)"] : {ERROR} Invalid output format.  Currently only csv and xml output supported."
        ;;
    esac
    str=$file_out" "$username@$host:$directory_scp  
    echo "["$(timestamp)"] : {NOTIFICATION} Attempting to scp "$outfile" to "$username@$host:$directory_scp" - [Started]"
    scp $str
    echo "["$(timestamp)"] : {NOTIFICATION} scp "$outfile" to "$username@$host:$directory_scp" - [Complete]"

done 

任何想法。我想捕获错误并格式化错误输出。

【问题讨论】:

  • 要么捕获/解析 mysql 可能吐出的任何输出,要么检查其退出代码?
  • 我该怎么做。你能举个例子吗?
  • $? 为您提供最后执行命令的退出代码。
  • 是的,我现在尝试了一点,但仍然无法接受错误并自己处理。
  • 错误通常被转储到 stderr,而您没有捕获该流。

标签: mysql bash error-handling


【解决方案1】:
 result=$(mysql --silent -h ${sql_server} -P 3306 -u${USER} -p${MYSQL_PASS} -D${DATABASE} -BNe "$sql_str")
    if [ $? -ne "0" ]; then
            echo "["$(timestamp)"] : {ERROR} MySQL error thrown in EOD DUMP"
    else
            while read -r line 

                   ...do something

【讨论】:

  • 在运行命令时我得到timestamp: command not found,然后是[] : {ERROR} MySQL error thrown in EOD DUMP
猜你喜欢
  • 1970-01-01
  • 2012-09-18
  • 2014-12-09
  • 1970-01-01
  • 1970-01-01
  • 2013-03-14
  • 1970-01-01
  • 2019-02-12
  • 2017-08-27
相关资源
最近更新 更多