Search code examples
mysqlbashmysql-error-1045

Bash user input Mysql login


Will start with what I am trying to accomplish. I wrote up a menu script to add a new database and echo back to screen the results. But can't seem to get it to login with a variable.

Heres the part I am having problems with:

#!/bin/bash
while [[ "$yn" != "Yes" && "$yn" != "Y" && "$yn" != "y" && "$yn" != "yes" ]]; do
    echo "  Please, type password for root user.             #"
read -r  mysqlrp
    echo "  You have entered $mysqlrp as your MySQL password #"
    echo "  Is this correct? (Yes or No)            #"
      read yn
done
mysql -u root -p$mysqlrp

have also tried:

mysql -u root -p${mysqlrp}

as well as mysql -u root -p'${mysqlrp}'

I get the following:

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)

even though when I try without the script works fine.

Please help, Thanks in advance, Joe


Solution

  • To supply a password directly in the command line string, you should use mysql --password=[password]. See this article.

    And to prompt the user for a password, you should probably use something like this.

    #!/bin/bash
    read -p "Username: " uname
    stty -echo
    read -p "Password: " passw; echo
    stty echo
    

    You must not ever print the password. And it should not be seen while typing it in either.


    #!/bin/bash
    read -p "Username: " uname
    stty -echo
    read -p "Password: " passw; echo
    stty echo
    mysql --user=$uname --password=$passw
    

    That script works for me. If it doesn't for you, please check that your mysql permissions allow you to login from localhost.