Drush for Developers - Second Edition

4 (2 reviews total)
By Juampy Novillo Requena
    What do you get with a Packt Subscription?

  • Instant access to this title and 7,500+ eBooks & Videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies

About this book

Drush for Developers, Second Edition, takes common challenges in Drupal projects and solves them using Drush. This book starts with the different installation approaches for Drush and its command structure. It then moves on to perhaps the trickiest challenge in Drupal projects: keeping code and configuration together during a project's lifetime. Next, we will deep dive into the tasks needed to keep a website under control and learn how to run, automate, and monitor them effectively.

Error validating and debugging our Drush commands is a must and this book has a whole chapter on that topic. The magic of managing remote Drupal projects through Drush site aliases is explained in the following chapters through a practical example. Finally, the book wraps up by putting in practice all the concepts covered in previous chapters in order to implement a development workflow for a team.

Publication date:
January 2015


Chapter 1. Introduction, Installation, and Basic Usage

Drush is a command-line interface for Drupal. It can also serve as an alternative to write scripts using PHP instead of BASH. The Drush ecosystem is vast. Every year, at DrupalCon, the Drush core team gives an update on the bleeding edge features being developed by them and by contributors all over the world.

Tasks such as clearing caches, running database updates, executing batch scripts, and managing remote websites are just a glimpse of what you can do with Drush.

Here is an example. Imagine that you have pushed new code for your website and need to run database updates. Normally this would involve the following steps:

  1. Back up your database.

  2. Open your web browser and navigate to http://example.com/user.

  3. Authenticate as administrator.

  4. Navigate to http://example.com/update.php.

  5. Run database updates and wait for a confirmation message.

Now, here is how you can accomplish the preceding steps with Drush:

$ drush @example.prod sql-dump > dump.sql
$ drush @example.prod updatedb --yes

That's it. We did not even have to open an SSH connection or a web browser. The first command created a database backup and the second one executed pending database updates. In both these commands, we used @example.prod, which is a Drush site alias used to load configuration details about a particular site. We will see Drush site aliases in detail in Chapter 5, Managing Local and Remote Environments.

Drush is highly customizable. You can adjust it to fit a specific workflow. This is especially helpful when working on a Drupal project within a team; you can define security policies, wrap commands with sensible defaults, sanitize a copy of the production database automatically, and so on. This is the area that this book will focus on. We will go through some common processes during a Drupal project and discover how we can automate or simplify them using Drush. Let's start!

This chapter is an introduction and will cover the following topics to get you up to speed:

  • Installation requirements

  • Drush command structure

  • Understanding Drush's context system


Installation requirements

The following are the installation requirements for Drush. If you have already installed it, simply make sure that you are running version 7.0.0-alpha5 (https://github.com/drush-ops/drush/releases/tag/7.0.0-alpha5) or higher by executing drush --version in the command line, and skip forward to the next section of this chapter.

Operating system

Drush works on Unix-like operating systems (such as Ubuntu and OSX) and Windows operating systems.

If you use Windows, consider using something like VirtualBox (https://www.virtualbox.org) to install a virtual machine that runs, for example, Ubuntu (http://www.ubuntu.com). If you still want to use Drush on Windows, there is an installer available at http://www.drush.org/drush_windows_installer. Note, however, that the installer installs an older version of Drush, so some of the contents of this book won't work.


Let's start by making sure that you have PHP 5.3.0 or greater installed. To do so, open a terminal and run the following command:

$ php -v

The output should look something like the following code screenshot:

As you can see, I am using PHP 5.5.9. If you get a Command not found message or your version is lower than 5.3.0, you will need to install or upgrade PHP. Refer to your vendor documentation to do this as the steps will vary.

Installing Composer

On Linux and OSX platforms, the recommended way to install Drush is through Composer (https://getcomposer.org), a dependency manager that has become the standard in the PHP world. Installing Composer can be accomplished with the following commands:

$ cd $HOME
$ curl -sS https://getcomposer.org/installer | php
$ sudo mv composer.phar /usr/local/bin/composer

If you find any issues while running the preceding commands or while installing it through a packaging system such as homebrew, then take a look at the official installation instructions for Composer (https://getcomposer.org/doc/00-intro.md#globally-on-osx-via-homebrew). Once you have completed the installation, you can verify that it works by running the following command:

$ composer about 
Composer - Package Management for PHP 
Composer is a dependency manager tracking local dependencies of your projects and libraries. 
See http://getcomposer.org/ for more information. 


If you have already installed Composer, make sure that it is up to date by running composer self-update (https://getcomposer.org/doc/03-cli.md#self-update).

Drush installation on Linux and OSX

At the time of writing this book, the latest available version of Drush is 7.0.0-alpha5 (https://github.com/drush-ops/drush/releases/tag/7.0.0-alpha5). This is the version that we will use. The Drush core team does a fantastic job of keeping backwards compatibility between major versions, so if you have already installed a more recent version of Drush, you should be okay as practically all the examples in the book will work.

Let's go ahead and install Drush. Once Composer has been installed (see the previous section on installing Composer), you can install Drush with the following command:

$ composer global require drush/drush:7.0.0-alpha5 -v
Changed current directory to /home/juampy/.composer
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
    - Installing drush/drush (7.0.0-alpha5)
    Downloading: 100%         
    Extracting archive
drush/drush suggests installing youngj/httpserver
Writing lock file
Generating autoload files

The preceding command has downloaded Drush 7.0.0-alpha5 into $HOME/.composer/vendor/bin/drush. In order to use Drush from anywhere in the system, we need to make sure that Composer's bin directory is present at our $PATH environment variable. We can do so with the following commands:

$ sed -i '1i export PATH="$HOME/.composer/vendor/bin:$PATH"' \
$ source $HOME/.bashrc

Note the use of $HOME and $PATH, which are environment variables. $HOME contains the location of your home directory, while $PATH represents a list of directories to look for executable files. You can view the contents of these variables by executing echo $HOME or echo $PATH. Take a look at your home directory to check whether there is .bash_profile, .bash_login, or .profile file at $HOME. If you find them, adjust the preceding commands, so the $PATH variable is adjusted in these files as well.

Finally, we can test that Drush has been installed successfully and contains the right version:

$ cd $HOME
$ drush --version
 Drush Version   :  7.0.0-alpha5

Manual installation

If you prefer to install Drush manually, then follow these steps:

  1. Start by opening a web browser, and download and uncompress the contents of Drush 7.0.0-alpha5 (https://github.com/drush-ops/drush/releases/tag/7.0.0-alpha5) into your home directory.

  2. Open a terminal and move the drush directory into your system's shared directory:

    $ sudo mv $HOME/drush /usr/share
  3. Set proper permissions to the drush executable file:

    $ sudo chmod u+x /usr/share/drush/drush
  4. Create a symbolic link of the Drush executable to any of the directories listed at your $PATH environment variable so that you do not have to type /usr/share/drush/drush every time you use it.

    $ echo $PATH
    $ sudo ln -s /usr/share/drush/drush /usr/local/bin/drush
  5. The next step consists of installing Composer dependencies for Drush:

    $ cd /usr/share/drush
    $ composer install
    Loading composer repositories with package information
    Installing dependencies (including require-dev) from lock file
     - Installing d11wtq/boris (v1.0.8)
     - Installing pear/console_table (1.1.5)
     - Installing phpunit/php-token-stream (1.2.2)
     - Installing symfony/yaml (v2.2.1)
     - Installing sebastian/version (1.0.3)
     - Installing sebastian/exporter (1.0.1)
     - Installing sebastian/environment (1.0.0)
     - Installing sebastian/diff (1.1.0)
     - Installing sebastian/comparator (1.0.0)
     - Installing phpunit/php-text-template (1.2.0)
     - Installing phpunit/phpunit-mock-objects (2.1.5)
     - Installing phpunit/php-timer (1.0.5)
     - Installing phpunit/php-file-iterator (1.3.4)
     - Installing phpunit/php-code-coverage (2.0.9)
     - Installing phpunit/phpunit (4.1.3)
     - Installing symfony/process (v2.4.5)
     pear/console_table suggests installing pear/Console_Color (>=0.0.4)
     phpunit/phpunit suggests installing phpunit/php-invoker (~1.1)
    Generating autoload files
  6. Finally, verify the installation:

    $ cd $HOME
    $ which drush
    $ drush --version
     Drush Version   :  7.0.0-alpha5

The main README file at the Drush repository has a great section on POST-INSTALL tasks (https://github.com/drush-ops/drush#post-install) with additional information on configuring PHP and extra settings for environments such as MAMP. It's worth taking a look at it.


The Drush command structure

Drush offers a broad list of commands that cover practically all the aspects of a Drupal project. If you are already fluent with executing commands in the terminal, you can skip this section. Otherwise, keep on reading to discover what arguments and options are and how these affect the behavior of a command.

We can view the available list of commands by running drush help. Additionally, running drush help some-command will show you detailed information about a particular command.

Executing a command

Let's start with a very simple command such as core-status, which prints environment information about Drush and, if available, a Drupal site. Assuming that we have a Drupal project installed at /home/juampy/projects/drupal, let's run this command here and see its output:

$ drush core-status
 Drupal version                  :  7.29-dev                        
 Site URI                        :  http://default                  
 Database driver                 :  mysql                           
 Database username               :  root                            
 Database name                   :  drupal7x                        
 Database                        :  Connected                       
 Drupal bootstrap                :  Successful                      
 Drupal user                     :                                  
 Default theme                   :  bartik                          
 Administration theme            :  seven                           
 PHP executable                  :  /usr/bin/php                    
 PHP configuration               :  /etc/php5/cli/php.ini           
 PHP OS                          :  Linux                           
 Drush version                   :  7.0.0-alpha5                    
 Drush temp directory            :  /tmp                            
 Drush alias files               :                                  
 Drupal root                     :  /home/juampy/projects/drupal    
 Site path                       :  sites/default                   
 File directory path             :  sites/default/files             
 Temporary file directory path   :  /tmp                

The preceding output informs us about the main configuration of the Drupal project plus some Drush environment settings.

Providing arguments to a command

The core-status command accepts a single argument that specifies which setting is to be retrieved (you can see this information by running drush help core-status). An argument is a string of text that acts as an input data for a command. Arguments are entered after the command name and are separated by spaces. Therefore, if we need to print just the items containing version in the setting name, we can execute the following command:

$ drush core-status version
 Drupal version   :  7.29-dev     
 Drush version    :  7.0.0-alpha5 

Drush commands might accept zero to any number of arguments depending on their nature. Beware that some commands expect arguments to be given in a certain order. For example, the variable-set command, used to change Drupal environment variables, requires the first argument to be the variable name and the second argument to be the variable's new value. Hence, the following example sets the site-name variable to the My awesome site value:

$ drush variable-set site-name "My awesome site"
site-name was set to "My awesome site".        [success]

Altering a command's behavior through options

Drush commands might accept options through the command line, which alter their default behavior. Options are in the form of --option-name or --option-name=value. Additionally, some options have a shorter version. For example, you can accept all confirmations for a Drush command by appending --yes or its shorter version: -y.

Let's take a look at options with an example. The core-status command has an option to show the database password. We will now add it to the command and inspect the output:

$ cd /home/juampy/projects/drupal
$ drush core-status --show-passwords database
 Database driver     :  mysql     
 Database username   :  root      
 Database password   :  mysecretpw          
 Database name       :  drupal7x  
 Database            :  Connected 

The --show-passwords option orders the core-status command that we want to see the database password of the Drupal site being bootstrapped.

Structuring command invocations

Excluding some exceptions, there is no strict ordering for options and arguments when you run a command. Besides, Drush does a great job parsing arguments and options no matter how we mix them up in the input. However, our commands will be more readable if we follow this pattern:

$ drush [global options] [command name] [command options] [arguments]

Here is an example:

$ drush --verbose core-status --show-passwords database 

And the following are the commands used in the previous example:

  • --verbose: This is a Drush global option. You can see all the available global options by running drush topic core-global-options.

  • core-status: This is the command that we are running.

  • --show-passwords: This is an option of the core-status command.

  • database: This is an argument for the core-status command.

Besides the fact of higher clarity by using the preceding structure, there are some commands in Drush that require options to be given in this order. This is the case of the core-sync Drush command, which is a wrapper of the actual Unix rsync command used to copy files and directories. Let's take a look at the following example:

$ drush rsync @self:%files/ /tmp/files --dry-run
You will destroy data from /tmp/files and replace with data from /home/juampy/projects/drupal/sites/default/files/
Do you really want to continue? (y/n):

The preceding command copies files recursively from a Drupal project into /tmp/files. The --dry-run option is an rsync specific option that attempts to copy files but does not make any actual changes. Now, let's try to run the same command but this time placing the option before the command name:

$ drush --dry-run rsync @self:%files/ /tmp/files
Unknown option: --dry-run.  See `drush help core-rsync` for available options. To suppress this error, add the option –strict=0.  [error]

We can see in the preceding output that Drush attempted to evaluate the --dry-run option and failed as it did not recognize it. This example demonstrates that you should carefully read the description of a command by running drush help command-name in order to understand its options, arguments, and ordering.

Command aliases

Most of Drush commands support a shorter name to be used when invoking them. You can find them in parenthesis next to each command name when running drush help, or in the Aliases section when viewing the full help of a command.

For example, the core-status command can also be executed with status or just st, which means that the following commands will return identical results:

$ drush core-status
$ drush status
$ drush st


For clarity, we will not use command aliases in this book, but these help us to work faster. So, it is worthwhile to use them.


Understanding Drush's context system

Drush is decoupled from Drupal. This means that it does not necessarily need a Drupal site to work with. Some commands do require a Drupal project to bootstrap, while for others, this might be optional. Let's take core-status as an example. This command gives us information about the current context. If we run this command outside of a Drupal project, we will obtain configuration details for Drush and our local environment:

$ cd $HOME
$ drush core-status
 PHP executable         :  /usr/bin/php                    
 PHP configuration      :  /etc/php5/cli/php.ini           
 PHP OS                 :  Linux                           
 Drush version          :  7.0.0-alpha5                    
 Drush temp directory   :  /tmp                            
 Drush alias files      :                                  

Now, if we change directory to a Drupal project, we will get extra information about it:

$ cd /home/juampy/projects/drupal
$ drush core-status
 Drupal version                  :  7.29-dev                        
 Site URI                        :  http://default                  
 Database driver                 :  mysql                           
 Database username               :  root                            
 Database name                   :  drupal7x                        
 Database                        :  Connected                       
 Drupal bootstrap                :  Successful                      
 Drupal user                     :                                  
 Default theme                   :  bartik                          
 Administration theme            :  seven                           
 PHP executable                  :  /usr/bin/php                    
 PHP configuration               :  /etc/php5/cli/php.ini           
 PHP OS                          :  Linux                           
 Drush version                   :  7.0.0-alpha5                    
 Drush temp directory            :  /tmp                            
 Drush alias files               :                                  
 Drupal root                     :  /home/juampy/projects/drupal    
 Site path                       :  sites/default                   
 File directory path             :  sites/default/files             
 Temporary file directory path   :  /tmp                        

In the preceding scenario, Drush finds out that it is currently at the root of a Drupal project that uses the default location to store its settings (sites/default). Therefore, it is able to bootstrap Drupal and load its configuration.


Setting the context manually

We do not have to be at the root of a Drupal project in order to run Drush commands against it. Instead, we can append additional options that will let Drush find it. For example, we could run the core-status command from a different directory, adding the --root option that points to the root of our Drupal project:

$ cd /home/juampy
$ drush --root=/home/juampy/projects/drupal core-status
 Drupal version                  :  7.29-dev                        
 Site URI                        :  http://default                  
 Database driver                 :  mysql                           
 Database username               :  root                            
 Database name                   :  drupal7x                        
 Database                        :  Connected                       
 Drupal bootstrap                :  Successful
 Drupal root                     :  /home/juampy/projects/drupal
 Site path                       :  sites/default

As we can see at the command output, Drush did bootstrap Drupal although we were not at its root directory. On a multisite Drupal installation, where settings.php is not at sites/default, we need to specify the site within our Drupal project that we want to bootstrap with the --uri option:

$ cd /home/juampy
$ drush --root=/home/juampy/projects/drupal --uri=mysite core-status
 Drupal version                  :  7.29-dev                        
 Site URI                        :  other_site                      
 Database driver                 :  mysql                           
 Database username               :  root                            
 Database name                   :  other_site                      
 Database                        :  Connected                       
 Drupal bootstrap                :  Successful                      
 Drupal root                     :  /home/juampy/projects/drupal
 Site path                       :  sites/mysite


This chapter was an introduction to the principles of Drush. We covered the installation requirements so that you could set them up on your local environment and then proceeded with the installation of Drush.

Next, we went through some command-line basics that involved how to invoke commands, and how to append options and arguments as well. We saw some caveats regarding the order of options and arguments and suggested a structure to construct command invocations that is easy to read.

The last section of the chapter gave some tips on how to set the context of a Drupal project for Drush. We saw that Drush is pretty intelligent and can automatically figure out whether we are on a Drupal project in order to bootstrap it, or we can alternatively pass extra options to inform where our Drupal project is.

In the next chapter, we will go through one of the most important challenges of developing Drupal projects and how Drush can help us with it: keeping configuration and code together.

About the Author

  • Juampy Novillo Requena

    Juampy Novillo Requena started working as a web developer in London. After spending a few years developing with plain PHP, Symfony, and Ruby on Rails, he discovered Drupal. Drawn by the Drupal community and the mind-blowing effect of getting a project done 10 times faster than before, Juampy has never looked back.

    Since then, he's become more and more involved in the issue queues, which in turn led him to become a maintainer of core and contributed modules. He organizes events, gives sessions at national and international conferences, and has written the book Drush User's Guide, Packt Publishing. He feels privileged to experiment, have fun, and be challenged every day. He is known as juampy on Drupal.org and IRC. His Twitter account is @juampynr.

    Browse publications by this author

Latest Reviews

(2 reviews total)
Drush for Developers - Second Edition
Unlock this book and the full library FREE for 7 days
Start now