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?
mysqlshow "test" > /dev/null 2>&1 && echo "Database exists."
Depending on the exit status of the mysqlshow command, it will execute the following echo.
The mysqlshow
path requires parsing the output (at least for the version of mysql I have) because it always returns success. Dale makes a very good point about differentiating between failures.
However, if you know that everything is running and you have correct credentials, etc, and you want to tell only whether the DB exists are not you can do it in one line with a blank sql command:
> mysql -uroot -ppassword good_db -e ''
> echo $?
0
> mysql -uroot -ppassword bad_db -e ''
ERROR 1049 (42000): Unknown database 'busker_core_locala'
> echo $?
1
Use the -e
option to the mysql
command. It will let you execute any query (assuming the right credentials).
This may be an example:
if mysql "DATABASE_NAME" -e exit > /dev/null 2>&1; then
echo "Exists"
else
echo "Not exists"
fi
mysqlshow
is a good tool for this, here is test to check the presence of the database database_name
if mysqlshow -p${MYSQL_ROOT} 2>/dev/null| grep -q "database_name"
then
echo "Database exist."
else
echo "Database does not exist."
fi
Or a simple oneliner
echo "Database "`mysqlshow -p${MYSQL_ROOT} 2>/dev/null| grep -q "database_name" || echo "does not "`"exist."
It's easy enough to reliably tell if the database exists with mysqlshow. The trick is being able to reliably tell the difference between a database not existing, or some other failure. The version of mysqlshow I have exits with a '1' in either case, so it can't tell.
Here's what I came up with to handle it. Adjust your mysqlshow command accordingly, or put your credentials in to a chmod 600
'd ~/.my.cnf file.
This works on Ubuntu 12 + 14. I haven't tested it in other environments yet:
#!/bin/bash -u
# Takes 1 argument. Aborts the script if there's a false negative.
function mysql_db_exists () {
local DBNAME="$1"
# Underscores are treated as wildcards by mysqlshow.
# Replace them with '\\_'. One of the underscores is consumed by the shell to keep the one mysqlshow needs in tact.
ESCAPED_DB_NAME="${DBNAME//_/\\\_}"
RESULT="$(mysqlshow "$ESCAPED_DB_NAME" 2>&1)"; EXITCODE=$?
if [ "$EXITCODE" -eq 0 ]; then
# This is never a false positive.
true
else
if echo "$RESULT" | grep -iq "Unknown database"; then
# True negative.
false
else
# False negative: Spit out the error and abort the script.
>&2 echo "ERR (mysql_db_exists): $RESULT"
exit 1
fi
fi
}
if mysql_db_exists "$1"; then
echo "It definitely exists."
else
echo "The only time you see this is when it positively does not."
fi
if [ $(mysqlshow DB 1>/dev/null 2>/dev/null) -eq 0 ]; then
echo "DB found"
fi