Main menu

How to write a (more useful) Drush command

3 May 2016

Welcome to part two of our miniseries on Drush commands! Do check out part one if you haven't already. There you'll see what we've been up to with our pretend module, my_awesome_module.

If you're writing a custom Drush command, it's pretty much guaranteed that you're needing to do something more complicated than write 'Hello World' to your database 5,000 times. Let's take a look at some Drush essentials.

Arguments and Options

You guessed it - just pass in an array. Simply give 'arguments' or 'options', and, for each one, a helpful description.

Validating options

In true Drupal style, there's a hook that allows you to validate the options and arguments input to your command. Simply implement drush_hook_validate() , where hook is the drush function you're validating options for. In there, you can get and check each of your options. Using drush_set_error() you can then output appropriate messages to the console. Try something like this:

Translated strings

Drush has its own basic version of Drupal's wonderful t() function. It's called dt() and you can use it much like t(), even with replacement arrays. Guide to dt()

Using this, we can redo our options from before as:

'arguments' => array( 'required_arg' => dt('Argument description for Drush to show on the help page'), ), 'options' => array( 'useful_option' => dt('Option description for Drush to show on the help page'), ),

Using the Batch API

Drupal's Batch API is super powerful and can be called from a variety of scenarios, including Drush commands! For a number of years, you needed a fair bit of additional boilerplate code to help Drush run batches, but in recent versions that's no longer necessary, allowing you to batch just as you would anywhere else. There's just one extra line now:

About the author

Nathan is a recent Masters of Computer Science graduate from the University of Warwick, and has lots of little chunks of experience in a variety of languages and arenas.
He is currently the main developer for our automated testing ambitions.