Checking if mysql user exists
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
As newer versions of MySQL allow this option:
DROP USER IF EXISTS 'username'@'host';
MySQL stores user data in a table called user
in a database named mysql
(by default). The following query will return 1
if a user with the specified username exists, 0
otherwise.
SELECT EXISTS(SELECT 1 FROM mysql.user WHERE user = 'username')
If you're deleting the MySQL user anyways, then there's really no need to check if it exists first. MySQL won't throw any errors if there's nothing to delete:
DELETE FROM mysql.user WHERE User = 'username';