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?
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!
I give +1 to answer by @chown, but here's another alternative: If the bash script is running locally with the MySQL instance, and you know the path to the datadir, you can test:
if [ -d /var/lib/mysql/databasename ] ; then
# Do Stuff ...
fi
This also assumes your shell user running the script has filesystem-level privileges to read the contents of the MySQL datadir. This is often the case, but it is not certain.
I couldn't get the accepted answer work for me (the grep
in the quotes didn't work), so here is my version:
RESULT=`mysql -u $USER -p$PASSWORD --skip-column-names -e "SHOW DATABASES LIKE 'myDatabase'"`
if [ "$RESULT" == "myDatabase" ]; then
echo "Database exist"
else
echo "Database does not exist"
fi
I used the option --skip-column-names
to remove the column names from the result.
YES
for db in $(mysql -u -p -N <<<"show databases like '%something%'")
do
case $db in
"something")
// do something
;;
"something else")
// do something else
;;
esac
done
mysql_user=<you_db_username>
mysql_pass=<you_db_passwrod>
target_db=<your_db_name>
if [ "`mysql -u${mysql_user} -p${mysql_pass} -e 'show databases;' | grep ${target_db}`" == "${target_db}" ]; then
echo "Database exist"
else
echo "Database does not exist"
fi
This executes a MySQL query to get all DB names, then greps to check that the required database exists.
I also used a slightly different version from chown's.
result=$(mysqlshow --user=root --password=12345 dbname | grep -v Wildcard | grep -ow dbname)
The above executes the given command and assigns the returned value to result
. And the w
option matches dbname
exactly.