Recover/Replace MySQL Root Password – UNIX

| | |

Forgetting or never having the root password for a MySQL database can be rather difficult if it is now your job to support it.

Note: You will need root access on the UNIX box to follow these commands.

# Debian / Ubuntu
sudo /etc/init.d/mysql stop

# CentOS / Red Hat
sudo /bin/systemctl stop mariadb
#sudo /bin/systemctl stop mysql
mysqld_safe --skip-grant-tables &
mysql -u root
use mysql;
update user set password=PASSWORD("NEW-ROOT-PASSWORD") where User='root';
flush privileges;
quit
# Debian / Ubuntu
sudo /etc/init.d/mysql stop
sudo /etc/init.d/mysql start

# CentOS / Red Hat
sudo /bin/systemctl stop mariadb
#sudo /bin/systemctl stop mysql
sudo /bin/systemctl start mariadb
#sudo /bin/systemctl start mysql

If for some reason you get an error saying mysql database doesn’t exist you may need to remove mysql/mariadb configuration files (/etc/my.cnf /etc/my.cnf.d/) or reinstall. Understand that that if you do that you may loose some or all data.

Originally Posted on November 19, 2015
Last Updated on December 30, 2016
All information on this site is shared with the intention to help. Before any source code or program is ran on a production (non-development) system it is suggested you test it and fully understand what it is doing not just what it appears it is doing. I accept no responsibility for any damage you may do with this code.