关于bash:在没有密码提示的情况下在Ubuntu上安装MySQL

Install MySQL on Ubuntu without a password prompt

如何编写在Ubuntu上安装mysql服务器的脚本?

将安装sudo apt-get install mysql,但它还将要求在控制台中输入密码。

我该如何以非交互方式完成这项工作?也就是说,编写一个可以提供密码的脚本?

1
2
3
4
5
#!/bin/bash
sudo apt-get install mysql  # To install MySQL server

# How to write script for assigning password to MySQL root user
# End


1
2
3
sudo debconf-set-selections <<< 'mysql-server mysql-server/root_password password your_password'
sudo debconf-set-selections <<< 'mysql-server mysql-server/root_password_again password your_password'
sudo apt-get -y install mysql-server

对于特定的版本,如mysql-server-5.6,您需要这样指定版本:

1
2
3
sudo debconf-set-selections <<< 'mysql-server-5.6 mysql-server/root_password password your_password'
sudo debconf-set-selections <<< 'mysql-server-5.6 mysql-server/root_password_again password your_password'
sudo apt-get -y install mysql-server-5.6

对于MySQL Community Server,密钥略有不同:

1
2
3
sudo debconf-set-selections <<< 'mysql-community-server mysql-community-server/root-pass password your_password'
sudo debconf-set-selections <<< 'mysql-community-server mysql-community-server/re-root-pass password your_password'
sudo apt-get -y install mysql-community-server

用所需的根密码替换您的密码。(对于空的根密码,您的_密码也可以保留为空。)

如果您的shell不支持这里的字符串(zsh、ksh93和bash支持这些字符串),请使用:

1
echo ... | sudo debconf-set-selections


这应该会起作用的

1
2
export DEBIAN_FRONTEND=noninteractive
sudo -E apt-get -q -y install mysql-server

当然,它会给你留下一个空白的根密码-所以你需要运行类似

1
mysqladmin -u root password mysecretpasswordgoeshere

然后向帐户添加密码。


另一种方法是:

1
2
3
echo"mysql-server-5.5 mysql-server/root_password password root" | debconf-set-selections
echo"mysql-server-5.5 mysql-server/root_password_again password root" | debconf-set-selections
apt-get -y install mysql-server-5.5

注意,这只是将密码设置为"root"。我不能让它用简单的引号''设置一个空密码,但这个解决方案对我来说已经足够了。

基于这里的解决方案。


用途:

1
2
3
sudo DEBIAN_FRONTEND=noninteractive apt-get install -y mysql-server

sudo mysql -h127.0.0.1 -P3306 -uroot -e"UPDATE mysql.user SET password = PASSWORD('yourpassword') WHERE user = 'root'"