Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Drush for Developers - Second Edition
Drush for Developers - Second Edition

Drush for Developers - Second Edition: Effectively manage Drupal projects using Drush

By Juan Pablo Novillo Requena , Juan P Novillo Requena
€16.99 €10.99
Book Jan 2015 180 pages 1st Edition
eBook
€16.99 €10.99
Print
€20.99
Subscription
€14.99 Monthly
eBook
€16.99 €10.99
Print
€20.99
Subscription
€14.99 Monthly

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details


Publication date : Jan 29, 2015
Length 180 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781784393786
Category :
Languages :
Concepts :
Table of content icon View table of contents Preview book icon Preview Book

Drush for Developers - Second Edition

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.

PHP

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. 

Note

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"' \
   $HOME/.bashrc
$ 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
    /home/juampy/.composer/vendor/bin:/usr/local/sbin:
      /usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:
      /usr/local/games
    $ 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
     /usr/local/bin/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

Note

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
 ...

Summary


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.

Left arrow icon Right arrow icon

Key benefits

What you will learn

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details


Publication date : Jan 29, 2015
Length 180 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781784393786
Category :
Languages :
Concepts :

Table of Contents

13 Chapters
Drush for Developers Second Edition Chevron down icon Chevron up icon
Credits Chevron down icon Chevron up icon
About the Author Chevron down icon Chevron up icon
About the Reviewers Chevron down icon Chevron up icon
www.PacktPub.com Chevron down icon Chevron up icon
Preface Chevron down icon Chevron up icon
Introduction, Installation, and Basic Usage Chevron down icon Chevron up icon
Keeping Database Configuration and Code Together Chevron down icon Chevron up icon
Running and Monitoring Tasks in Drupal Projects Chevron down icon Chevron up icon
Error Handling and Debugging Chevron down icon Chevron up icon
Managing Local and Remote Environments Chevron down icon Chevron up icon
Setting Up a Development Workflow Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Filter icon Filter
Top Reviews
Rating distribution
Empty star icon Empty star icon Empty star icon Empty star icon Empty star icon 0
(0 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 0%
1 star 0%

Filter reviews by


No reviews found
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.