10
Nov

How to create a custom Drush command?

10 Nov
Drush is a shell interface for managing Drupal right from your server command line. It is a very useful tool as it helps you perform various admin tasks using just one or two commands in the terminal, replacing the need for many clicks and page refreshes in the UI.  It comes by default with a bunch of useful commands, such as downloading, enabling or even updating modules.
First of all you need to create a new custom module for building the command.
The module should contain the following files:
- new_module.drush.inc
- new_module.module
- new_module.info


The new_module module functionality we want to expose to Drush, it’s a function that sets the Hello world! message:
print_0.png

There are 2 main components in the Drush command architecture: the hook implementation where we define the commands and their configurations, and the callback functions that get triggered by the command. 

First, let’s implement 
hook_drush_command() and define a simple command calleddrush-demo-command with an alias of ddc:
dush_command.png

The second part of the Drush command architecture is the callback function. As it is now, Drush expects a function to be declared called drush_drush_demo_command() This default naming structure starts with drush followed by the name of the command all connected with underscores. So let’s quickly declare it and use it to call the demo_drush_print_statement() function we wrote earlier:

command_drush.png

Now if you clear the drush cache drush cc all, you can run the "drush ddc" command and you should see Hello world! printed to the screen. Now the new command should work.


 
Leave A Comment