Reset your MySQL root password
✓ Published0🌍 Public
TThomasG77
Last edited Jan 24, 2024
Created on Jan 24, 2024
This example demonstrates a command-line procedure for resetting a MySQL root password on a localhost server. It shows two distinct methods: a simple, hardcoded password approach and a more secure alternative that generates a random alphanumeric password using shell tools like `strings`, `grep`, and `head`. The code executes `sudo service mysql stop`, writes an `ALTER USER` SQL statement to an init file, then launches `mysqld` with the `--init-file` flag before restarting the service. The recipe relies on standard Unix utilities and the MySQL command-line client, with no graphical visualization or charting library involved.
AI-generated descriptionReset your MySQL root password
Only used on localhost so did not feel concerned about the password weakness here
sudo service mysql stop
echo "ALTER USER 'root'@'localhost' IDENTIFIED BY 'basicPassword1234';" >| $HOME/mysql-init
sudo mysqld --init-file=$HOME/mysql-init &
sudo service mysql start
Then
sudo mysql -p # and type your password here basicPassword1234
Alternative recipe by generating a password
sudo service mysql stop
mypassword=$(strings /dev/urandom | grep -o '[[:alnum:]]' | head -n 30 | tr -d '\n'; echo
)
echo ${mypassword} # as it's generated, you need to keep trace of the password to put in your password manager
echo "ALTER USER 'root'@'localhost' IDENTIFIED BY '"${mypassword}"';" >| $HOME/mysql-init
sudo mysqld --init-file=$HOME/mysql-init &
sudo service mysql start
Then
sudo mysql -p # and type generated password here