bash 执行mysql查询后捕获退出代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21025126/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 09:12:23  来源:igfitidea点击:

Catching exit code after executing mysql query

mysqlbashshellbatch-fileerror-handling

提问by andresg3

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.

我正在编写一个将查询 mysql 的 bash 脚本。我想添加一些错误检查。假设以下查询由于某种原因失败,我想捕获退出错误并退出脚本。例如,这是我脚本的一部分。

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.

在脚本运行“$QUERY”后,我如何捕获退出代码。我在想这样的事情。但它似乎不起作用。

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

Any ideas

有任何想法吗

回答by fedorqui 'SO stop harming'

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 ...