Check if mysql database exists, perform action based on result

前端 未结 20 2033
傲寒
傲寒 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:36

    FWIW, the auth_socket plugin makes this much easier. The question may be super old, but there are still people like me coming here for inspiration.

    If your script is running as root, you can do this:

    DBNAME="what_you_are_looking_for"
    DBEXISTS="$(mysql -u root -e "show databases like '$DBNAME'" --batch --skip-column-names)"
    

    If the database exists, then $DBNAME = $DBEXISTS.

    If the database does not exist, then $DBEXISTS = "".

    Both should have an exit status of 0, so you can still use non-zero statuses to report errors, rather than letting a non-existent database appear as an error.

    0 讨论(0)
  • 2021-02-01 16:38

    Following command should do the trick for both the cases,

    mysqlshow "DB_NAME" &> /dev/null && echo "YES" || echo "NO"
    
    0 讨论(0)
提交回复
热议问题