Search code examples
mysqlbashubuntuapt

Install MySQL on Ubuntu without a password prompt


How do I write a script to install MySQL server on Ubuntu?

sudo apt-get install mysql will install, but it will also ask for a password to be entered in the console.

How do I do this in a non-interactive way? That is, write a script that can provide the password?

#!/bin/bash
sudo apt-get install mysql  # To install MySQL server

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

Solution

  • 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
    

    For specific versions, such as mysql-server-5.6, you'll need to specify the version in like this:

    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
    

    For mysql-community-server, the keys are slightly different:

    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
    

    Replace your_password with the desired root password. (it seems your_password can also be left blank for a blank root password.)

    If you writing a script then your shell may be not bash but dash/ash or some basic unix shell. These shells, unlike zsh, ksh93 and bash, doesn't support here-strings <<<. So you should use:

    echo ... | sudo debconf-set-selections 
    

    Or a more readable print of multiline strings:

    cat << EOF | sudo debconf-set-selections
    mysql-server mysql-server/root_password password your_password
    mysql-server mysql-server/root_password_again password your_password
    EOF
    

    You can check with debconf-get-selections command:

    $ sudo debconf-get-selections | grep ^mysql
    mysql-server    mysql-server/root_password_again    password    your_password
    mysql-server    mysql-server/root_password  password    your_password