Skip to content

Instantly share code, notes, and snippets.

@sorohan
Last active October 24, 2016 03:18
Show Gist options
  • Save sorohan/8534434 to your computer and use it in GitHub Desktop.
Save sorohan/8534434 to your computer and use it in GitHub Desktop.
Reset mysql root password on unix without needing old password.
#!/bin/bash
MYSQL_ROOT_PASSWORD=$1
if [ -z "$MYSQL_ROOT_PASSWORD" ]; then
echo 'Missing required $1 (password).'
exit 1
fi
# check if mysql is running now.
mysqlrunning=$(service mysqld status | grep 'running')
if [ ! -z "$mysqlrunning" ]; then
echo "stopping mysql"
service mysqld stop
fi
echo "starting with skip grants"
mysqld_safe --skip-grant-tables >/dev/null 2>&1 &
sleep 10
# Get pid to kill later.
PID_FILE=$(echo 'show variables like "pid_file"' | mysql --defaults-file=/dev/null -N -u root | awk '{print $2}')
PID=$(cat $PID_FILE)
echo "resetting pw"
mysql --defaults-file=/dev/null -u root mysql << EOF
UPDATE mysql.user SET Password=PASSWORD('$MYSQL_ROOT_PASSWORD') WHERE User='root';
FLUSH PRIVILEGES;
EOF
sleep 10
echo "stopping mysql"
kill $PID
# restart mysql if was running before.
if [ ! -z "$mysqlrunning" ]; then
echo "starting mysql as normal"
sleep 5
service mysqld start
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment