Reset root MySQL password on Ubuntu

This is a question I have heard (too) many time. How does one reset the root MySQL password on Ubuntu. In order to make this as simple as possible I created a shell script (you can see it below) that does just that.

What does it do?

I’m glad you ask, because just trusting someone on the internet probably isn’t such a great idea. I have added a couple of comments to the script in order to make it more readable, so please look over it before you use it.

Here is exactly what the script does:

  1. Asks for confirmation
  2. Stops MySQL
  3. Starts MySQL without grant tables
  4. Waits a couple of seconds for MySQL to start
  5. Generates new password of random length
  6. Changes root password in MySQL
  7. Stops insecure MySQL
  8. Starts the MySQL service again
  9. Exits and prints your new password

How to:

  1. Save the script locally on the MySQL host
  2. Run the script as root or using sudo
$ sudo bash mysql_pwd_reset.sh
  1. Save the new password
  2. Delete the script, just in case

The Script