Using Drush

This is quick overview of using Drush, or the Drupal shell, for updating and managing Drupal web sites. Attempting to administer Drupal through its GUI is a pain, but Drush allows you to run updates and alter your configuration quickly on the command line. Best of all, Drush is fully scriptable and provides its own API so you can develop software to do exactly what you need.

While you can use Drush to update, clone and migrate Drupal sites, I’d still use something like Git to track your code changes and revert them if necessary.

(All commands shown here were executed on Ubuntu 12.04 server.)

Part I: Installing Drush

Instructions here.

Drush allows you to set up aliases to refer to Drupal sites or groups of sites. Aliases can also be specific to a particular site, multi-site install, user or system depending on where you place your alias files. To set up a system-wide alias file:

$ mkdir /etc/drush
$ vi aliases.drushrc.php

Aliases are expressed as arrays in PHP code:

$aliases['mysite'] = array (
  'root' => '/var/www/mysite/',
  'uri' => 'mysite.com',
  'databases' =>
  array (
    'default' =>
    array (
      'default' =>
      array (
        'database' => 'mysite_db',
        'username' => 'mysite_user',
        'password' => 'My password',
        'host' => 'localhost',
        'port' => '',
        'driver' => 'mysql',
        'prefix' => '',
      ),
    ),
  ),
);

This allows you to execute Drush commands using the credentials of the aliased Drupal site no matter where you are on your filesystem:

$ drush @mysite core-status "Drupal Version"
Drupal version : 7.23

Aliases can also refer to remote Drupal sites, or lists of Drupal sites:

$aliases['everything'] = array (
   'site-list' => array('@mysite', '@mysite2'),
);

This could allow you to update a bunch of Drupal sites at once without having to visit their GUIs individually.

Part II: Using Drush to Set Up a Drupal Site and Modules

You can install a Drupal web site from scratch:

$ drush dl drupal
$ cd drupal
$ drush si minimal --db url=mysql://YourMySQLUser:YourPassword@localhost/YourDrupalDatabase --db-su=name --db-su-pw=password --site-name="My Drupal Site"

(The su is your “root” database user and password. This allows Drupal to set up your database for you. You may also want to run the Drupal standard install instead of the minimal one.)

To install the Webform module:

$ drush @mysite pm-download webform
$ drush @mysite pm-enable webform

If you want to install old, development, alpha, etc. releases of Drupal and its modules, you can do:

$ drush dl drupal --select --all

Part III: Some Useful Commands

Remember that Drush commands are context-sensitive. Unless you specify a Drupal installation, each command refers to the site in the directory where the command is run.

All commands take the form “drush [command]”.

CommandPurpose
ccSelect cache(s) to clear for the current web site
@mysite cc allClear all caches of an aliased web site
@mysite core-statusSee the details of an existing Drupal installation
site-aliasSee all defined alias records
@mysite search-reindexForce a site’s search index to be rebuilt
@mysite variable-set [variable-name]
@mysite variable-get [variable-name]
@mysite variable-delete [variable-name]
Set/retrieve/delete records from the Variables table
@mysite user-create [name]
@mysite user-cancel [name]
@mysite user-password [name]
@mysite user-add-role [name]
Create/cancel/reset password/add role for a specified user account
@mysite sql-cliOpen a database command-line interface using the credentials in the specified site’s settings.php
@mysite sql-dumpDump the specified database (equivalent to mysqldump)
@mysite sql-query “SELECT * FROM users;”Execute a query against the specified site’s database

For a list of all available commands, type drush help.

Part IV: Update Your Web Site(s)

I frequently use Drush’s update features, since they’re way more convenient than clicking your way through the GUI.

All commands take the form “drush [command]”.

CommandPurpose
@mysite pm-download webform –select –allSelect a version of the Webform module for download (if you omit –select –all, Drush defaults to the latest recommended version)
@mysite pm-updatecodeUpdate core Drupal and modules to latest recommended releases
@mysite pm-updatecode –security-onlyInstall security updates only
@mysite updatedbUpdate your site’s database after applying code updates
@mysite pm-update OR
@mysite up
Apply all code and database updates for a site (equivalent to pm-updatecode followed by updatedb)
@mysite pm-updatecode –lock=webformPrevent a module from being updated (Webform will stay locked until you issue the command drush @mysite pm-updatecode –unlock=webform.)
@mysitelist updatedbRun database updates using a site-list you’ve defined, per Step 1 above

Part V: Using Drush Extensions

Various modules and add-ons, like the Devel module, drush_make, and drush_extras, offer Drush extensions that give you additional commands and flexibility. Use the –filter flag to list any additional capabilities included with a new module.

$ drush @mysite pm-download devel
$ drush @mysite pm-enable devel
$ drush @mysite help --filter=devel
 devel-download        Downloads the FirePHP library from http://firephp.org/.
 devel-reinstall       Disable, Uninstall, and Install a list of projects.
 (dre)
 devel-token (token)   List available tokens
 fn-hook (fnh, hook)   List implementations of a given hook and explore source of specified one.
 fn-view (fnv)         Show the source of specified function or method.

Part VI: Using Drush to Clone or Migrate a Web Site

In many Drupal setups, you’ll have development, staging, and production sites that will need to be synchronized or pushed into public view. Drush provides some easy ways to clone your code base and databases from one site to another.

To create a development instance of your site, first make sure your site aliases are set up as per Step 1 above. Next, create a place for your cloned site to live, then create a database for it.

$ mkdir /var/www/dev_site
$ cd /var/www/dev_site
$ drush dl drupal --drupal-project-rename=Site_name_here
$ cd example
$ drush site-install minimal --db-url='mysql://[db_user]:[db_pass]@localhost/[db_name]' --site-name=Example

Clone your code base:

$ drush core-rsync @mysite @my_dev_site

This copies all the files from @mysite to @my_dev_site. If you add the –include-conf option, Drush will copy the settings.php file as well. I typically don’t bother, but either way your dev site needs a settings.php file with its correct database credentials.

Finally, clone your database:

$ drush sql-sync @mysite @my_dev_site

So now you have a development site which is a clone of your production site. (If you clone your site, and find you can’t log in, try copying in the default .htaccess file from core Drupal.) Thereafter, to sync the two sites back and forth, you just need to run the sync commands again:

$ drush core-rsync @mysite @my_dev_site
$ drush sql-sync @mysite @my-dev_site --create-db

(The –create-db option empties the database before cloning it.)

Part VII: Shell Scripting

The final topic I’ll touch on here is shell scripting. Drush provides an in-place replacement for your preferred shell (bash, csh, etc.). That means you can write scripts that interact with both your operating system and Drupal. Note that Drush scripts are expressed in PHP.

#!/usr/bin/env drush
drush_print(dt("Hello! This site's name is: @name", array("@name" => variable_get('site_name', 'unknown'))));

You can run this like any other shell script, and you can do pretty much anything that a typical shell script can do, such as processing command-line arguments, prompting the user for input, or running shell commands.

// list the command line arguments
while ($arg = drush_shift()){
  drush_print(' ' . $arg);
}

// run a shell command
drush_op_system("ls -al");

// prompt the user for input
$name = drush_prompt("Please enter your name: ");
echo "Your name is $name!n";

You can call Drush commands like this:

// clears the 'all' cache for current web site
drush_invoke('cache-clear', 'all');

/* drush_invoke_process is similar to drush_invoke, but it creates a new process in a new Drupal instance, so you need to specify a site alias */
$site_record = drush_sitealias_get_record('@mysite');
drush_invoke_process($site_record, 'cache-clear', array('all'));

This just scratches the surface of scripting with Drush. Check out the extensive API documentation for the use of hook_drush_command() and hook_drush_help(), as well as the extensive list of Core Drush commands. You can automate database backups, synchronization, Git pulls, and pretty much anything else you can imagine.

Loading

Leave a Reply

Your email address will not be published. Required fields are marked *