Check if mysql database exists, perform action based on result

前端 未结 20 2056
傲寒
傲寒 2021-02-01 16:02

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?

20条回答
  •  星月不相逢
    2021-02-01 16:16

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

提交回复
热议问题