Checking if mysql user exists

前端 未结 7 1552
被撕碎了的回忆
被撕碎了的回忆 2021-02-02 09:20

How can I check if a user exists?

Im doing an installer for a mysql database, and I need to check if a user exits, if not create user, if yes delete user and create it a

7条回答
  •  闹比i
    闹比i (楼主)
    2021-02-02 10:05

    This is how I was able to do it:

    #!/usr/bin/env bash
    
    set -o errexit
    set -o nounset
    
    # Create credentials file
    echo -e "[client]\nuser=root\npassword=${MYSQL_ROOT_PASSWORD}" > ~/.my.cnf
    
    # Create standard user and grant permissions
    if ! echo "SELECT COUNT(*) FROM mysql.user WHERE user = 'myuser';" | mysql | grep 1 &> /dev/null; then
        echo "Creating database user ..."
        echo "CREATE USER 'myuser'@'localhost' IDENTIFIED BY 'mypassword';
              GRANT ALL PRIVILEGES ON mydatabase.* TO 'myuser'@'localhost';
              FLUSH PRIVILEGES;" | mysql
    else
        echo "Database user already created. Continue ..."
    fi
    

    Change myuser, mydatabase and mypassword accordingly.

提交回复
热议问题