Connect to MySQL through command line without using root password?

Solution 1:

Both for MySQL and PostgreSQL you can specify your user and password in local config file. .my.cnf for MySQL and .pgpass for PostgreSQL. These files should be in your home directory (i.e. ~/.my.cnf).

.my.cnf:

[mysql]
user=user
password=password

.pgpass:

host:port:database:user:password

You can have a wildcard entry here, substituting any field for *******.

PS: DO NOT EVER SPECIFY A PASSWORD ON THE COMMAND LINE! This can be perfectly visible with ps if your system is not configured to not show processes that belongs to other users.

@thinice: If you want to create those files really secure you should do:

umask 077
touch .my.new.config
umask 022 # or whatever was your default

This way the file would be created with secure permissions from the start and no eavesdropper would have a chance leeching your password.

PostgreSQL will refuse to use the file with permissions higher the 0600 anyway.

Solution 2:

mysql_config_editor set --login-path=storedPasswordKey --host=localhost --user=root --password

How do I execute a command line with a secure password?? use the config editor!!!

As of mysql 5.6.6 you can store the password in a config file and then execute cli commands like this....

mysql --login-path=storedPasswordKey ....

--login-path replaces variables... host, user AND password. excellent right!


Solution 3:

Don't put quotes around the password because if you do the quotes are considered to be part of the password.


Solution 4:

MYSQL_USER="root"
MYSQL_PASSWORD="PASSWORD"
DBNAME="DB_NAME"

mysql -u$MYSQL_USER -p$MYSQL_PASSWORD -e "CREATE DATABASE $DBNAME;" 2> /tmp/error1

STATUS=$? 
if [ $STATUS -eq 0 ];
then 
    echo -e "Database '$DBNAME' is created"
elif (grep -i "^ERROR 1007" /tmp/error1 > /dev/null);
then
    echo -e "Database '$DBNAME' already exists"
else
    echo -e "Failed to create database '$DBNAME'"
fi

rm -r /tmp/error1 

This will do the trick Thanks