Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash check mysql connect

Tags:

linux

bash

mysql

I'm writing a bash script to do some operations against a database on my debian squeeze Server.

I have noticed that if I enter a wrong password for root, the prompt will be closed and I won't be asked to try again... that's not very convenient!

So I was trying to create a loop that attempts to connect to MYSQL and save the password for later if successful.

I tried this, but it doesn't work. Instead, I receive this error:

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)

read -s -p "Enter MYSQL root password: " mysqlRootPassword

while [[ -n `mysql -u root -p$mysqlRootPassword` ]]; do
       read -p "Can't connect, please retry: " mysqlRootPassword
done

I am not very experienced in bash scripting, any help would be awesome!

like image 849
Erwan Avatar asked Aug 31 '11 03:08

Erwan


1 Answers

I don't think you need the [[ -n backtic ... ]]; test nested like that. Try:

read -s -p "Enter MYSQL root password: " mysqlRootPassword

while ! mysql -u root -p$mysqlRootPassword  -e ";" ; do
       read -s -p "Can't connect, please retry: " mysqlRootPassword
done

while evaluates any command group upto a closing ; do and checks the return code of last command executed to determine if the loop should be executed. Because you are looking for a failure, you have to precede the test with a logical NOT (!) OR you can use the syntactic equivalent, i.e.

until mysql -u root -p$mysqlRootPassword  -e ";" ; do
       read -s -p "Can't connect, please retry: " mysqlRootPassword
done

which you can think of as 'until mysql works correctly, keep trying to get the right password'.

Unfortunately, I don't have access to a mysql installation, so this is untested.

I hope this helps.

like image 146
shellter Avatar answered Oct 14 '22 01:10

shellter