Checking if mysql user exists

前端 未结 7 1556
被撕碎了的回忆
被撕碎了的回忆 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条回答
  •  南方客
    南方客 (楼主)
    2021-02-02 09:56

    When in need to check if a user exists without deleting it (for instance when just skipping some instructions instead of executing them in any case), one can use this (where $USER is the user to check):

    if [ $(echo "SELECT COUNT(*) FROM mysql.user WHERE user = '$USER'" | mysql | tail -n1) -gt 0 ]
    then
      echo "User exists"
    else
      echo "User doesn't exist"
    fi
    

    NB:

    • mysql command requires extra args and/or configuration for authentication)
    • tail -n1 is used for removing the query result header

提交回复
热议问题