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
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.