Skip to content

Instantly share code, notes, and snippets.

@lnrsoft
Forked from sorohan/mysql-reset-root-pw.sh
Last active October 25, 2016 01:24
Show Gist options
  • Save lnrsoft/68dae7ae21cc0fcbcc4ce950bed85b25 to your computer and use it in GitHub Desktop.
Save lnrsoft/68dae7ae21cc0fcbcc4ce950bed85b25 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 user set authentication_string=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