开发者

bash check mysql connect

开发者 https://www.devze.com 2023-04-01 02:30 出处:网络
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 as

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 atte开发者_运维百科mpts 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!


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号