Writing custom commands for Drush: the Drupal swiss army knife.

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 #!/usr/bin/env drush or #!/full/path/to/drush and using
    Drush commands
  • using Drush php interpreter #!/full/path/to/drush php-script and using the Drush
    PHP api
  • writing custom commands

This guide is about the last case.

Continue reading “Writing custom commands for Drush: the Drupal swiss army knife.”