MySQL 将脚本中的密码视为数据库

MySQL treats password in script as database

我是 Bash 脚本的新手。我想为我创建一个登录 MySQL 的脚本:

PASSWORD="MyPassword"

sudo service mysql start

mysql -u root -p $PASSWORD

但是,它抛出一个错误,告诉我我的密码 ($PASSWORD) 不是数据库。

有什么办法吗?

谢谢,抱歉,如果我问的是 RTFM 或 UTFM。

来自man mysql

If you use the short option form (-p), you cannot have a space between the option and the password.

所以要么

mysql -u root -p"$PASSWORD"

mysql -u root --password "$PASSWORD"

在命令行中使用密码是不安全的。

来自 mysql 用户指南:

This is convenient but insecure. On some systems, your password becomes visible to system status programs such as ps that may be invoked by other users to display command lines.

我建议您使用 mysql_config_editor 实用程序来存储您的数据库凭据。

mysql_config_editor set --login-path=YOUR_LOGIN_PATH --host=YOUR_HOST --user=YOUR_DB_USER --password

然后它会交互询问密码

之后您可以连接到您的数据库:

mysql --login-path=YOUR_LOGIN_PATH YOUR_DB

示例(设置凭据):

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

示例(在您的脚本中连接到数据库):

mysql --login-path=root YOUR_DB