custom Drush commands
Blog

Writing custom Drush commands in Drupal 7

As a drupal developer we use drush on daily basis. For example clearing the cache, downloading or enabling modules/themes, updating modules. All these commands comes with core but drupal also provides hooks to integrate with our custom modules.

Today we are discussing about how we can write drush commands through our custom module. We are taking example - “Count of nodes by type”.

$ drush node-count 

or

$ drush nc 

Example of using & output:

$  drush node-count article
article’s node count : 100

To achieve these we have to hook_drush_command(). Let’s create module called custom_dc, And check these code.

/**
 * Implementation of hook_drush_command().
 */
function custom_title_drush_command() {
  $items = array();
  $items['node-count'] = array(
    'callback' => 'custom_title_node_count',  // Callback function
    'description' => 'Drush command to get node count of particular node type.',
    'aliases' => array('nc'), // alias of command
    'examples' => array(      // List these example when user types : drush help nc
      'Get all nodes count' => 'drush nc',
      'Get articles node count' => 'drush nc article',
      'Get articles, pages node count' => 'drush nc article page',
    ),
  );
  return $items;
}

/*
 * Callback function for hook_drush_command().
 */
function custom_title_node_count() {
  // Get arguments passed in command, Ex: drush nc page blog
  $args = func_get_args();
  if ($args) {
    // Loop for types
    foreach($args as $type){
      // Query to get count of particular type
      $result = db_select('node', 'n')
        ->fields('n', array('nid'))
        ->condition('type', $type, '=')
        ->execute();
      $num_of_results = $result->rowCount();
      drush_print($type. "'s node count : " . $num_of_results);
    }

  }
  // If no type passed then return total count
  else {
    drush_print('No node types mentioned');

    $result = db_select('node', 'n')
      ->fields('n', array('nid'))
      ->execute();
    $num_of_results = $result->rowCount();

    drush_print('Count of all nodes : '. $num_of_results);
  }
}

This hook defined command “node-count”. 

Some points about hook_drush_command() implementation.

  • callback : These is callback function for these command.
  • alias :  Alias of these command, here ‘nc’ is alias so we can run command like these Ex: drush nc blog
  • examples :  Array of examples where it will display by help command
$ drush help nc
Drush command to get node count of particular node type.
Examples:
 Get all nodes count                       drush nc              
 Get articles node count                   drush nc article      
 Get articles, pages node count            drush nc article page
Aliases: nc

How to use newly created drush commands - Get all nodes count

drush nc

Get article nodes count

drush nc article

Get page nodes count

drush nc page

Get page, blog nodes count

drush nc page, blog