I have a bash script that needs to perform a couple actions in MySQL. So far I have something like this:
我有一个bash脚本,需要在MySQL中执行一些操作。到目前为止,我有这样的事情:
#!/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
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.
这很有效,直到它与具有空密码的MySQL用户名一起使用。用户在我的密码提示符处按Enter键,但随后他们再次收到来自MySQL的“输入密码”的提示。
How can I avoid this second password prompt and make the script deal with both blank and non-blank passwords?
如何避免此第二个密码提示并使脚本处理空白和非空密码?
2 个解决方案
#1
2
Check if the password is blank or not, and if it is, then omit the -p switch altogether.
检查密码是否为空,如果是,则完全省略-p开关。
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
Later edit to avoid a whole if-then-else block:
稍后编辑以避免整个if-then-else块:
command="/usr/bin/mysql -u $sqluname"
[ -n "$sqlpasswd" ] && command="$command -p$sqlpasswd"
eval $command
#2
2
You'd need to specify the -n
switch if $sqlpasswd is empty (instead of -p $sqlpasswd
).
如果$ sqlpasswd为空(而不是-p $ sqlpasswd),则需要指定-n开关。
#1
2
Check if the password is blank or not, and if it is, then omit the -p switch altogether.
检查密码是否为空,如果是,则完全省略-p开关。
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
Later edit to avoid a whole if-then-else block:
稍后编辑以避免整个if-then-else块:
command="/usr/bin/mysql -u $sqluname"
[ -n "$sqlpasswd" ] && command="$command -p$sqlpasswd"
eval $command
#2
2
You'd need to specify the -n
switch if $sqlpasswd is empty (instead of -p $sqlpasswd
).
如果$ sqlpasswd为空(而不是-p $ sqlpasswd),则需要指定-n开关。