[Drupal] An intorduction on custom Drush commands with and without arguments
Drush commands are not the strangers for drupal developers. We use drush to clear cache, enable-disable modules, install-uninstall modules, set variables and even more.
To create a custom drush command use the following:
Create a module (for eg. my_module).
Create my_module.drush.inc file and implement hook_drush_command() hook.
/**
* Implements hook_drush_command().
*
* @return
* An associative array describing your command(s).
*/
function my_module_drush_command() {
return array(
'new-command' => array(
'description' => dt('Sample command description.'),
),
);
}
Here new-command is the command we are creating. When we type,
drush new-command
there should be some function to execute. Then the callback have a specific syntax like,
drush_my_module_new_command
We are trying to print a sentence on executing the drush command. Here is the complete callback,
/**
* Sample command description comment.
*/
function drush_my_module_new_command() {
drupal_set_message('Hai, this is me');
}
Now lets check whether the drush command has been created or not. Open the terminal and type
drush new-command
It must output: Hai, this is me
If you have not implemented the callback for drush command in right syntax, don't worry on executing the same on terminal will give you an error likes this. For eg., you did some mistake on the callback for new-command, when we execute the same on terminal, it will throw an exception like this.
No hook functions were found for new-command.
The primary hook function is [error] drush_my_module_new_command().
Please implement this function.
Run with --show-invoke to see all available hooks.
We can also pass an argument along with the drush command in terminal. Here is the complete callback for this,
/**
* Put the site in local development mode.
*/
function drush_my_module_new_command($value) {
if ($value == 'true') {
drupal_set_message('Hai, this is true');
}
elseif ($value == 'false') {
drupal_set_message('Hai, this is false');
}
else {
drupal_set_message('Hai, this is nothing');
}
}
Here we are passing an argument along with the drush command. If the argument we passed is true.
That is,
drush new-command true;
It must output: Hai, this is true
drush new-command false;
Output will be: Hai, this is false
For others, like
drush new-command fahg;
OR
drush new-command;
It will output: Hai, this is nothing
Don't worry if you are stuck on wrong declaration of the callback. Now try to create new drush commands it can provide more on exploring.
Please let us know if we can provide any further assistance.