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?
Also you can ask to use the database and then handle the exit code.
$ if mysql -uroot -pxxx -e "USE mysql"; then echo "exists"; fi
exists
$ if mysql -uroot -pxxx -e "USE doesnotexist"; then echo "exists"; fi
ERROR 1049 (42000) at line 1: Unknown database 'doesnotexist'
Or inspect $? after the call.
mysqlshow will not show underscore characters '_' in the database name.
mysqlshow $DOMAIN %
https://dev.mysql.com/doc/refman/5.1/en/mysqlshow.html
If it helps, I did this for MariaDB on Debian Stretch:
DB_CHECK=$(mysqlshow "${DB_NAME}" | grep "Unknown database") 1> /dev/null
if [ ! -z "${DB_CHECK}" ]; then
echo "Database found."
else
echo "Database not found."
fi
Short explanation: The result of mysqlshow
for database name in variable $DB_NAME
is checked for "Unknown database". If that string is found it's put into variable $DB_CHECK
. Then finally the -z
comparison checks if the $DB_CHECK
variable is empty.
If $DB_CHECK
is empty then "Unknown database" did not appear in the mysqlshow
response. Probably not 100% reliable, like if the connection failed or whatever. (I've not tested that.)
Here is an alternate version:
RESULT=`mysql -u$USER -p$PASSWORD -e "SHOW DATABASES" | grep $DATABASE`
if [ "$RESULT" == "$DATABASE" ]; then
echo "Database exist"
else
echo "Database does not exist"
fi
IF there is a DB named abcd
and we use -Fo
after grep
then for the search result of DB a
/ab
/abc
the script will show the result Database exist
.
Another solution without grep
:
FOUND_DATABASES=`MYSQL_PWD="${DB_PASSWORD}" mysql \
-u "${DB_PASSWORD}" \
--skip-column-names \
--batch \
-e "SHOW DATABASES LIKE '${DB_NAME}'" | wc -l`
FOUND_DATABASES:
Notes:
MYSQL_PWD
to disable the warning:
mysql: [Warning] Using a password on the command line interface can be insecure.
--skip-column-names
to hide columns
--batch
to disable borders like +-----------+
Here's how i did it inside a bash script:
#!/bin/sh
DATABASE_USER=*****
DATABASE_PWD=*****
DATABASE_NAME=my_database
if mysql -u$DATABASE_USER -p$DATABASE_PWD -e "use $DATABASE_NAME";
then
echo "Database $DATABASE_NAME already exists. Exiting."
exit
else
echo Create database
mysql -u$DATABASE_USER -p$DATABASE_PWD -e "CREATE DATABASE $DATABASE_NAME"
fi