Check if mysql database exists, perform action based on result

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

    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
    

提交回复
热议问题