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