Linux bash 检查 mysql 连接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7252236/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
bash check mysql connect
提问by Erwan
I'm writing a bash script to do some operations against a database on my debian squeeze Server.
我正在编写一个 bash 脚本来对我的 debian 挤压服务器上的数据库执行一些操作。
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!
我注意到如果我输入了错误的root密码,提示将被关闭,并且不会要求我重试......这不是很方便!
So I was trying to create a loop that attempts to connect to MYSQL and save the password for later if successful.
所以我试图创建一个循环,尝试连接到 MYSQL 并在成功时保存密码以备后用。
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)
错误 1045 (28000): 用户 'root'@'localhost' 访问被拒绝(使用密码: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!
我在 bash 脚本方面不是很有经验,任何帮助都会很棒!
采纳答案by shellter
I don't think you need the [[ -n backtic ... ]];
test nested like that. Try:
我认为您不需要[[ -n backtic ... ]];
像那样嵌套测试。尝试:
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.
while
评估任何命令组直到关闭; do
并检查最后执行的命令的返回代码以确定是否应该执行循环。因为您正在寻找失败,所以您必须在测试之前使用逻辑 NOT ( !
) 或者您可以使用等效的语法,即
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'.
您可以将其视为“直到 mysql 正常工作,请继续尝试获取正确的密码”。
Unfortunately, I don't have access to a mysql installation, so this is untested.
不幸的是,我无权访问 mysql 安装,所以这是未经测试的。
I hope this helps.
我希望这有帮助。