How to auto login in MySQL from a shell script?

Alternative ways to write these options.

You can write

mysql -u "$MYSQL_ROOT" -p"$MYSQL_PASS" -e "SHOW DATABASES"

If [password is] given, there must be no space between --password= or -p and the password following it. If no password option is specified, the default is to send no password.

to pass empty strings as separate arguments. Your comment below indicates that the client will still ask for a password, though. Probably it interprets the empty argument as a database name and not as the password. So you could try the following instead:

mysql --user="$MYSQL_ROOT" --password="$MYSQL_PASS" -e "SHOW DATABASES"

.my.cnf file

But even if there is a way, I’d still suggest you use a ~/.my.cnf file instead. Arguments on the command line are likely included in a process listing generated by ps -A -ocmd, so other users can see them. The .my.cnf file, on the other hand, can (and should) be made readable only by you (using chmod 0600 ~/.my.cnf), and will be used automatically. Have that file include the following lines:

[client]
user=root
password=

Then a simple mysql -e "SHOW DATABASES" will suffice, as the client will obtain its credentials from that file.

See 6.1.2.1. End-User Guidelines for Password Security for the various ways in which you can provide a password, and their respective benefits and drawbacks. See 4.2.3.3. Using Option Files for general information on this .my.cnf file

Leave a Comment

tech