在bash脚本的MySQL密码输入 [英] MySQL password input in bash script
问题描述
我有需要执行MySQL中的几个操作的bash脚本。到目前为止,我有这样的事情:
I have a bash script that needs to perform a couple actions in MySQL. So far I have something like this:
#!/bin/sh
read -p "Enter your MySQL username: " $sqluname
read -sp "Enter your MySQL password (ENTER for none): " $sqlpasswd
/usr/bin/mysql -u $sqluname -p $sqlpasswd << eof
*some SQL stuff*
eof
直到它与具有空白密码的MySQL用户名采用这种运作良好。用户点击ENTER我的密码提示,但随后他们收到另一个提示从MySQL到请输入密码了。
This works well until it's used with a MySQL username that has a blank password. The user hits ENTER at my password prompt, but then they receive another prompt to "Enter your password" again from MySQL.
我怎样才能避免这种第二个密码提示,使脚本处理既空白和非空白密码?
How can I avoid this second password prompt and make the script deal with both blank and non-blank passwords?
推荐答案
检查密码为空或没有,如果是,则省略-p开关完全
Check if the password is blank or not, and if it is, then omit the -p switch altogether.
read -p "Enter your MySQL username: " $sqluname
read -sp "Enter your MySQL password (ENTER for none): " $sqlpasswd
if [ -n "$sqlpasswd" ]; then
/usr/bin/mysql -u $sqluname -p $sqlpasswd << eof
else
/usr/bin/mysql -u $sqluname << eof
fi
后来编辑,以避免整体的if-then-else块:
Later edit to avoid a whole if-then-else block:
command="/usr/bin/mysql -u $sqluname"
[ -n "$sqlpasswd" ] && command="$command -p$sqlpasswd"
eval $command
这篇关于在bash脚本的MySQL密码输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!