5

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

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?

2
  • 1
    Does it work if you replace $sqlpassword with "$sqlpassword"? Commented May 9, 2012 at 2:20
  • Nope.................... Commented May 9, 2012 at 16:08

2 Answers 2

3

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

Later edit to avoid a whole if-then-else block:

command="/usr/bin/mysql -u $sqluname"
[ -n "$sqlpasswd" ] && command="$command -p$sqlpasswd"
eval $command
Sign up to request clarification or add additional context in comments.

3 Comments

That will work. I was kinda hoping there was a tidier way than an if/then/else block, but this works fine anyway.
Hmm you could try this instead of the whole block if you want something shorthand: [ -n "$sqlpasswd" ] && command = "$command -p$sqlpasswd"
+1 for the first variant; the second version feels like it is more trouble than it is worth.
2

You'd need to specify the -n switch if $sqlpasswd is empty (instead of -p $sqlpasswd).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.