1

I have written a script that handles all of the steps for setting up a website on our server. The problem I am running into is that, if someone enters the wrong MySQL password, the script keeps going and just skips creating a database. I want it to stop if the password is incorrect, and ask for it again.

How can I handle this?

Here is my code -

read -s -p "Enter the MySQL password: " BASEPASS
mysql -u ${BASEUSER} -p${BASEPASS} <<CREATE_DB_QUERY
CREATE DATABASE IF NOT EXISTS ${NEWDB};
CREATE USER ${NEWUSER} IDENTIFIED BY '${NEWPASS}';
GRANT ALL ON ${NEWDB}.* TO ${NEWUSER};
CREATE_DB_QUERY

mysqldump --opt --user=${BASEUSER} --password=${BASEPASS} ${BASEDB} > ${SQLFILE}
mysql --user=${BASEUSER} --password=${BASEPASS} ${NEWDB} < ${SQLFILE}
rm ${SQLFILE}
1
  • 2
    Can't you just let mysql prompt for the password itself (by removing the read altogether and giving the -p option without an argument)? Mar 20, 2018 at 1:44

1 Answer 1

1

First, make sure you set -o errexit -o nounset at the top of the script. Then loop through a simple check until you've got at least a valid password:

while true
do
    read -s -p "Enter the MySQL password: " BASEPASS
    mysql -u "$BASEUSER" "-p${BASEPASS}" 'SELECT 1' && break
done

Also, Use More Quotes™!

1
  • And, thanks for the use more quotes comment/resource. I am new to Shell, so am still figuring out this stuff. Mar 23, 2018 at 10:46

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .