How to pass password to mysql command line

You have to be very careful how you pass passwords to command lines as, if you're not careful, you'll end up leaving it open to sniffing using tools such as ps.


The safest way to do this would be to create a new config file and pass it to mysql using either the --defaults-file= or --defaults-extra-file= command line option.

The difference between the two is that the latter is read in addition to the default config files whereas with the former, only the one file passed as the argument is used.

Your additional configuration file should contain something similar to:

[client]
user=foo
password=P@55w0rd

Make sure that you secure this file.

Then run:

mysql --defaults-extra-file=<path to the new config file> [all my other options]

The mysql client utility can take a password on the command line with either the -p or --password= options.

If you use -p, there must not be any blank space after the option letter:

$ mysql -pmypassword

I prefer the long options in scripts as they are self-documenting:

mysql --password=mypassword --user=me --host=etc

create a file ~/.my.cnf, make it only accessible by yourself, permission 600.

   [client]
   user=myuser
   password=mypassword

Then you don't need type password any more.

   bash$ mysql -u myuser mydatabase
   mysql>