Drupal 7 – Write a Drush command which takes arguments input

Previously:

 

So it would be more useful if our drush command could take input arguments. Let’s modify the eureka_drush.drush.inc a bit.

eureka_drush.drush.inc

<?php

/**
 * Implementation of hook_drush_command().
 */
function eureka_drush_drush_command() {
  $items = array();
  
  $items['say-hello'] = array(
    'description' => 'Say Hello to someone',
    'arguments' => array(
      'whom' => 'Someone you want to say hello to. Defaults to "Kit".',
    ),
    'drupal dependencies' => array('eureka_drush'),
  );
  
  return $items;
} 

/**
 * Callback function for say-hello.
 * The function name is drush_<module_name>_<command_in_underscore>
 */
function drush_eureka_drush_say_hello($whom = "Kit") {
  $msg = 'Hello ' . $whom;
  drush_print("\n" . $msg . "\n");
}

 

Try this.

drush say-hello Eureka!

drush-hello-world-3
 

If you want to take dynamic number of arguments, you could try
eureka_drush.drush.inc

<?php

/**
 * Implementation of hook_drush_command().
 */
function eureka_drush_drush_command() {
  $items = array();
  
  $items['say-hello'] = array(
    'description' => 'Say Hello to someone',
    'drupal dependencies' => array('eureka_drush'),
  );
  
  return $items;
} 

/**
 * Callback function for say-hello.
 * The function name is drush_<module_name>_<command_in_underscore>
 */
function drush_eureka_drush_say_hello() {
  $args_count = func_num_args();
  $args = func_get_args();
  
  for ($i = 0; $i < $args_count; $i++) {
    drush_print("Hello " . $args[$i]);
  }
}

 

Let’s say more HELLOs…

drush say-hello Eureka! Kit 2015

drush-hello-world-4
 

Done =)

Reference: PHP – func_get_args

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s