Open Source Software Technical Articles

Want the Best of the Wazi Blogs Delivered Directly to your Inbox?

Subscribe to Wazi by Email

Your email:

Connect with Us!

Current Articles | RSS Feed RSS Feed

How to install WordPress from the command line

  
  
  

Most people install WordPress through its web interface using a browser. This is the officially supported installation method, and it's easy and intuitive. But did you know you can also install WordPress from the Linux command line?

There are good reasons for installing WordPress from the shell:

  • It's easy and convenient – The default WordPress installation process requires that users know how to upload files by FTP, create MySQL databases, and assign users to them. Those tasks may be showstoppers for people who want to use WordPress but aren't technically proficient.
  • It's faster – If you're performing a large number of WordPress installations, it's dull and time-consuming to repeatedly follow the default installation procedure.
  • It offers improved security – A shell script to install WordPress can be secure and restrictive. Without one, WordPress users need FTP and MySQL access, and you cannot really control what they do with that.
  • It provides flexibility and customization – A shell script installation allows you to modify the default WordPress installation and do things such as adding or customizing plugins and themes.

Steps in WordPress installations

Each WordPress installation, regardless of the way it is performed, should go through certain basic stages:

  1. Provision of user-specific data for the installation, such as fully qualified domain name (FQDN), subdirectory, tables prefix, and admin password.
  2. Download of installation package.
  3. Configuration of wp-config.php, the main WordPress configuration file.
  4. Population of the database.
  5. Optional customization, including adding templates or plugins.

You can complete all of these steps from the Bash shell.

Provision of user-specific data

To start, you need to know where WordPress should be installed and what the admin details will be. You can pass this information to Bash via command-line parameters to the script. In a Bash script the variable $1 contains the first argument, $2 the second, and so on.

By taking advantage of specifically numbered, command-line parameters you can use the script as an API or top-level script for other scripts. By contrast, if you provided variables interactively, such as through dialogues, you would not be able to call the script from other scripts if you wanted to.

For the WordPress installation you need the directory where the software will reside on your web server's filesystem, plus the blog title and an admin email address and password:

filesystem_directory=$1
blog_title=$2
admin_email=$3
admin_pass=$4

Suppose that you want to install WordPress under the directory /var/www/example.org/ with blog title "Example blog," admin email admin@example.org, and password "secret_pass." In such a case you should execute from the Linux command line ./install_script.sh '/var/www/example.org/html/' 'Example blog' 'admin@example.org' 'secret_pass'.

When you use a script that accepts arguments, it is a good idea to check for the right number of arguments and give instructions about the proper use of the script if the number of arguments is incorrect. You can check for the necessary four arguments with the following Bash code:

if [ $# != 4 ]
then
    echo "Usage: `basename $0` filesystem_directory blog_title admin_email admin_passw"
    exit 1
fi

For WordPress you also need to specify MySQL details, but instead of specifying them manually you can generate them with code like this:

db_name="wp`date +%s`"
# The database user is the same as the database name.
db_user=$db_name
db_password=`date |md5sum |cut -c '1-12'`

For the database name (db_name) specify first a prefix such as wp that indicates what the database is about, then add the current Unix timestamp (date +%s) to ensure that the name is unique. You can generate a strong, random database password by using the first 12 characters from the md5sum of the current date. If you need the database username and password later you can get them from WordPress's wp-config.php file.

Download the WordPress installation package

The next step, the download of the WordPress installation package, is the easiest one. You can always find the latest WordPress installation archive at http://wordpress.org/latest.tar.gz. You can download the file to a temporary location so that it is available for reuse in subsequent WordPress installations. The script can use a simple conditional to download the file only if it has not been downloaded already:

# First check if the file has been ever downloaded
if test -f /tmp/latest.tar.gz
then
    echo "File is already there."
# Download the file for the first time
else
    echo "Downloading file file for the first time"
    cd /tmp/ && wget "http://wordpress.org/latest.tar.gz"
fi

Saving the file to /tmp is convenient but not necessarily secure; anyone with access to the /tmp directory may tamper with it. Also, you must remember to delete the old installation file from your download directory whenever you need to install a new version of WordPress with your script.

Extraction of the files and configuration of wp-config.php

To extract the installation package use the command /bin/tar -C $filesystem_directory -zxf /tmp/latest.tar.gz --strip-components=1. The argument -C specifies where the extracted files should be placed. The argument --strip-components instructs tar to remove the leading directory from the installation package, which is always "wordpress." If you don't specify this argument your files will be extracted to $filesystem_directory/wordpress/ instead of just $filesystem_directory.

Once the files are extracted you have to set ownership of them to the owner and group under which the Apache web server runs. For CentOS this is user nobody, group nobody. To change the files' ownership recursively run the command chown nobody: $filesystem_directory -R.

Next, rename the main configuration file from wp-config-sample.php to wp-config.php in the root WordPress directory with the command /bin/mv $filesystem_directory/wp-config-sample.php $filesystem_directory/wp-config.php.

Now you can start changing the values in wp-config.php. Begin with the database details. By default they look like this:

 
/** The name of the database for WordPress */
define('db_name', 'database_name_here');

/** MySQL database username */
define('db_user', 'username_here');

/** MySQL database password */
define('db_password', 'password_here');

To replace the default values with our custom values you can use the sed utility with the -i argument to edit the configuration file in place:

/bin/sed -i "s/database_name_here/$db_name/g" $filesystem_directory/wp-config.php
/bin/sed -i "s/username_here/$db_user/g" $filesystem_directory/wp-config.php
/bin/sed -i "s/password_here/$db_password/g" $filesystem_directory/wp-config.php

Next, look at the part of the configuration file called "Authentication Unique Keys and Salts." These settings are important to the security of your WordPress installation and specifically the encryption of passwords and cookies.

Because the keys and salts part is in the middle of the configuration file there is no easy way to populate it directly, especially from a Bash script. However, you can use a workaround. First, copy all the configuration lines starting from the line containing table_prefix to a temporary file, like this: grep -A50 'table_prefix' $filesystem_directory/wp-config.php > /tmp/wp-temp-config. The argument -A50 means that grep catches the matching line and 50 lines after it, which takes us to the end of the document.

Next, remove the default keys and salts values with the command /bin/sed -i '/**#@/,/$p/d' $filesystem_directory/wp-config.php. To define where the keys and salts start, WordPress uses a particular combination of characters: **#@. The variable $p in sed means the end of the file. Thus this sed command deletes all lines between these special characters, and removes the lines you previously backed up to the file /tmp/wp-temp-config.

Now you have to get random values for the keys and salts via the WordPress API, which is accessible at the https://api.wordpress.org/secret-key/1.1/salt/. To use the API in your script run the command:

/usr/bin/lynx --dump -width 200 https://api.wordpress.org/secret-key/1.1/salt/ >> $filesystem_directory/wp-config.php

This command downloads the remote content – that is, the complete part for the generated salts and keys – and appends it to the configuration file. The argument --width prevents incorrect text wrapping, which otherwise corrupts the code.

Finally, restore the previously backed up content from /tmp/wp-temp-config and remove the temporary file. Use the command /bin/cat /tmp/wp-temp-config >> $filesystem_directory/wp-config.php && rm /tmp/wp-temp-config -f.

Population of the database

The next step is to create a new database and assign a user to it. You can use the MySQL client from Bash like this:

/usr/bin/mysql -e "CREATE DATABASE $db_name"
/usr/bin/mysql -e "GRANT ALL PRIVILEGES ON $db_name.* to '"$db_user"'@'localhost' IDENTIFIED BY '"$db_password"';"

In order to execute these commands you must have an administrator MySQL username and password saved in the ~/.my.cnf file. If you don't, specify the user and password in the command line with the arguments -u for username and -p for password.

Next, import the default WordPress installation database. Stick to the default WordPress installation procedure and avoid custom hacks – use the native WordPress function wp_install. This function accepts as arguments a blog title, admin username, admin password, admin email address, and public flag, which indicates whether the blog can be indexed by search engines. The wp_install function has to be invoked by the PHP interpreter via /usr/bin/php and its --run option for running code on the command line.

To be able to use the WordPress function wp_install, you have to include the file wp-admin/install.php first so that all the necessary variables, constants, functions, and classes are loaded recursively. Thus, your script's code should be:

/usr/bin/php -r "
include '"$filesystem_directory"/wp-admin/install.php';
wp_install('"$blog_title"', 'admin', '"$admin_email"', 1, '', '"$admin_pass"');
" > /dev/null 2>&1

This code populates all the necessary MySQL tables just as WordPress would through a standard web installation. It provides a vanilla, unmodified WordPress installation procedure that is guaranteed to work with future versions unless WordPress makes a major change in the installation process.

After all of the above steps complete you should be able to log in to your new WordPress site with the username admin and the password you have specified.

Once you know how to install WordPress from the command line you should be able to install any web application in a similar manner. The most important thing is to try keeping as close as possible to the default installation procedure.

Here is the entire install script in one piece:

#!/bin/bash
# Command line WordPress installation script by Anatoliy Dimitrov

# Get input
filesystem_directory=$1
blog_title=$2
admin_email=$3
admin_pass=$4

# Validate input
if [ $# != 4 ]
then
    echo "Usage: `basename $0` filesystem_directory blog_title admin_email admin_passw"
    exit 1
fi

# Generating needed variables
db_name="wp`date +%s`"
# The database user is the same as the database name.
db_user=$db_name
db_password=`date |md5sum |cut -c '1-12'`

# First check if the file has been ever downloaded
if test -f /tmp/latest.tar.gz
then
    echo "File is already there."
# Download the file for the first time
else
    echo "Downloading file file for the first time"
    cd /tmp/ && wget "http://wordpress.org/latest.tar.gz"
fi

# Extract the installation archive
/bin/tar -C $filesystem_directory -zxf /tmp/latest.tar.gz --strip-components=1

# Fix the ownership of the files
chown nobody: $filesystem_directory -R

# Rename the default config file
/bin/mv $filesystem_directory/wp-config-sample.php $filesystem_directory/wp-config.php

# Substitute the default database values
/bin/sed -i "s/database_name_here/$db_name/g" $filesystem_directory/wp-config.php
/bin/sed -i "s/username_here/$db_user/g" $filesystem_directory/wp-config.php
/bin/sed -i "s/password_here/$db_password/g" $filesystem_directory/wp-config.php

# Get the salts and keys
/bin/grep -A50 'table_prefix' $filesystem_directory/wp-config.php > /tmp/wp-temp-config
/bin/sed -i '/**#@/,/$p/d' $filesystem_directory/wp-config.php
/usr/bin/lynx --dump -width 200 https://api.wordpress.org/secret-key/1.1/salt/ >> $filesystem_directory/wp-config.php
/bin/cat /tmp/wp-temp-config >> $filesystem_directory/wp-config.php && rm /tmp/wp-temp-config -f

# Create the database
/usr/bin/mysql -e "CREATE DATABASE $db_name"
/usr/bin/mysql -e "GRANT ALL PRIVILEGES ON $db_name.* to '"$db_user"'@'localhost' IDENTIFIED BY '"$db_password"';"

# Populate the database
/usr/bin/php -r "
include '"$filesystem_directory"/wp-admin/install.php';
wp_install('"$blog_title"', 'admin', '"$admin_email"', 1, '', '"$admin_pass"');
" > /dev/null 2>&1

Do you want to receive a compilation of Wazi's top
blog posts in the past year delivered directly to your inbox?






This work is licensed under a Creative Commons Attribution 3.0 Unported License
Creative Commons License.

Comments

Amazing post. Seriously the best docs I could find on setting up a customized install via bash. I was easily able to build on this and add just about everything I needed.Everything works perfectly, but I'm having an issue at the very last step - populating the install page. I cannot seem to get it to work. Does the fact that I'm on nginx have anything to do with the last part? Or permissions? I'm stumped. Any ideas? 
 
Again - thanks for the script, it was a great starting point.
Posted @ Saturday, April 12, 2014 10:42 PM by Greg Reindel
For the last step, you need the php cli, usually /usr/bin/php. It shouldn't matter what web server you use.
Posted @ Sunday, April 13, 2014 12:42 AM by Anatoliy Dimitrov
With regards to the sort sporting activities your are usually enjoying, there is a replica hermes handbags regarding contact lenses for you personally. Additionally, there are sun shades accessible who have a couple of interchangeable contact lenses that can be used for almost any problem. That is suited to those who carry out many different types regarding sporting activities. You can even thought we would have got both the particular outdated trend ear canal supports or perhaps use a tie, which is often beneficial in case you are carrying out intense routines. Additionally, there are lots artist sun shades regarding replica prada bags available nowadays. Since many females ponder over it being a need to to fit the particular brand names regarding colors which they wear with all the garments they will use, the harder popular garments traces have commenced branching out there to be able to vision use. Orlando Dior and also Versace have got introduced they will traces regarding could artist chanel replica handbags. They're almost all extremely stylish and also worthy of virtually any garments which you chanel replica. And also for your males that are followers of the brand names, you should not get worried simply because they have introduced traces that have been especially created for guys. Yet since constantly, given that they're artist brand names, you can aid yet inquire about the values. Thankfully the business are usually polite adequate of these consumers and possess introduced less costly replica chanel handbags, which usually nonetheless retain the school of these more costly counterparts.
Posted @ Thursday, July 17, 2014 9:33 PM by louis vuitton outlet
Post Comment
Name
 *
Email
 *
Website (optional)
Comment
 *

Allowed tags: <a> link, <b> bold, <i> italics