检查mysql数据库是否存在,根据结果执行动作 [英] Check if mysql database exists, perform action based on result

查看:73
本文介绍了检查mysql数据库是否存在,根据结果执行动作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以从bash脚本中检查mysql数据库是否存在.然后根据结果执行其他操作还是终止脚本?

Is it possible from within a bash script to check if a mysql database exists. Depending on the result then perform another action or terminate the script?

推荐答案

示例脚本(感谢Bill Karwin的--user--password注释!):

Example script (Thanks to Bill Karwin for the --user and --password comment!):

#!/bin/bash
## --user=XXXXXX --password=XXXXXX *may* not be necessary if run as root or you have unsecured DBs but
##   using them makes this script a lot more portable.  Thanks @billkarwin
RESULT=`mysqlshow --user=XXXXXX --password=XXXXXX myDatabase| grep -v Wildcard | grep -o myDatabase`
if [ "$RESULT" == "myDatabase" ]; then
    echo YES
fi

以下是在提示符下运行时的命令外观:

These are what the commands look like when run at a prompt:

[root@host ~]# mysqlshow myDatabase
Wildcard: myDatabase
+------------------+
|    Databases     |
+------------------+
| myDatabase       |
+------------------+

如果不存在数据库,则输出将如下所示:

If no DB exists, the output will look like this:

[root@host ~]# mysqlshow myDatabase
Wildcard: myDatabase
+-----------+
| Databases |
+-----------+
+-----------+

然后,解析输出并根据输出是否存在做您需要做的事情!

Then, parse the output and do what you need to based on if it exists or not!

这篇关于检查mysql数据库是否存在,根据结果执行动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆