Check if mysql database exists, perform action based on result

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

    Example script (Thanks to Bill Karwin for the --user and --password comment!):

    #!/bin/bash
    ## --user=XXXXXX --password=XXXXXX *may* not be necessary if run as root or you have unsecured DBs but
    ##   using them makes this script a lot more portable.  Thanks @billkarwin
    RESULT=`mysqlshow --user=XXXXXX --password=XXXXXX myDatabase| grep -v Wildcard | grep -o myDatabase`
    if [ "$RESULT" == "myDatabase" ]; then
        echo YES
    fi
    

    These are what the commands look like when run at a prompt:

    [root@host ~]# mysqlshow myDatabase
    Wildcard: myDatabase
    +------------------+
    |    Databases     |
    +------------------+
    | myDatabase       |
    +------------------+
    

    If no DB exists, the output will look like this:

    [root@host ~]# mysqlshow myDatabase
    Wildcard: myDatabase
    +-----------+
    | Databases |
    +-----------+
    +-----------+
    

    Then, parse the output and do what you need to based on if it exists or not!

提交回复
热议问题