Recently I worked on a client project based on the Drupal platform.
The most important part of the job was automating a data import from a remote source,
but instead of writing a script to do the job, I created a command for Drush.
Quoting from Drush repository site
Drush is a command-line shell and scripting interface for Drupal, a veritable Swiss Army knife designed to make life easier for those who spend their working hours hacking away at the command prompt.
Drush can handle almost every aspect of a Drupal site, from the mundane cache management to
user management, from packaging a Drupal install into a makefile to
project management and much more, including a CLI for running sql queries an http server for development and an rsync wrapper.
Drush commands can also be executed on remote machines, provided Drush is installed, by specifing the server alias (e.g.
drush clear-cache @staging).
There are different ways of creating Drush scripts:
- prepending the script with the shebang
- using Drush php interpreter
#!/full/path/to/drush php-scriptand using the Drush
- writing custom commands
This guide is about the last case.
Drush commands are much like Rake or Grunt tasks, you give them a name (more like a namespace) and Drush figures out what function must be called.
To create a Drush command, follow these simple steps
- create a
namespace.drush.incin one of the standard import path
- implement the
namespace_drush_commandentry point function
- implement the command functions. By conventions the command functions are called
Drush search for commandfiles in the following locations:
- system-wide drush commands folder, e.g.
- .drush folder in
sites/all/drushin the current Drupal installation
- all enabled modules folders in the current Drupal installation
Implementing the command
To implement a Drush command, the script must implement the drush_command hook.
This function must return a data structure containing all the informations that define your custom command.
As an example we will develop a command that rolls a dice and prints the result.
diceroller as namespace and
roll-dice as command name.
This is the implementation of the main hook function
The command is easily implementd this way
In this case we assume that the
--rolls option contains a number, but we can guarantee that the function parameters are valid implementing the
validate hook (there are others called just before and after the real command function).
If we did our job diligently, running
drush help roll-dice should give us this ouput
Consult the Drush api for a complete list of hooks functions and constants or launch
drush topic docs-api from the command line.
For a complete implementation of a command example, see
drush topic docs-examplecommand.