Supercharge Your Drupal Workflow: Building Custom Drush Command for Productivity

Drupal Custom Drush Command

In Drupal 9, the custom Drush command file should have a .drush.yml extension instead of .drush.inc.

  1. Create a custom module: Create a custom module named “my_custom_module” by following Drupal’s module development guidelines.
  2. Create the drush.services.yml file: Inside the my_custom_module module directory, create a drush.services.yml file.
  3. Define the command service: Open the drush.services.yml file and define your custom Drush command as a service. Here’s the content of the drush.services.yml file:
services:
  utilities.commands:
    class: \Drupal\utilities\Commands\CustomUtilities
    tags:
      - { name: drush.command }
  1. Create the command class: Create a new PHP class named CustomUtilities in the utilities/src/Commands directory. The class should extend the DrushCommands class provided by Drush. Here’s an example of the CustomUtilities class:
<?php

namespace Drupal\utilities\Commands;

use Drush\Commands\DrushCommands;
use Drupal\Core\Entity\EntityTypeManagerInterface;
/**
 * A Drush commandfile.
 *
 * In addition to this file, you need a drush.services.yml
 * in root of your module, and a composer.json file that provides the name
 * of the services file to use.
 */
class CustomUtilities extends DrushCommands {
  /**
   * Echos back hello with the argument provided.
   *
   * @command bot
   * @param string $arg1
   *   The first argument.
   * @param string $arg2
   *   The second argument.
   * @option string $option1
   *   The first option.
   * @option string $option2
   *   The second option.
   * @aliases d9-bot
   * @usage bot [arg1] [arg2] --option1=value --option2=value
   *   Execute my custom command.
   */
  public function bot($arg1, $arg2, $options = ['option1' => NULL, 'option2' => NULL]) {
      $this->output()->writeln('Hello ' . $arg1 . ','. $arg2 . '! Passed options are:'. $options['option1']. ' & '. $options['option2'] );
  }

}

In the example above, the CustomUtilities class fetches the user input argument and displays it as console output.

Refer to the below screens for folder structure,

Drupal Custom Drush Command Folder Structure

  1. Clear the Drush cache: After creating the command file and the command class, clear Drush’s cache by running the following command in your Drupal root directory:
drush cache:clear drush
  1. Test the command: Finally, you can test your custom Drush command by running it in the command line:
drush bot Sankar Prakash --option1=Drupal --option2=React

See the below output from the custom drush command function.

Custom Drush Command

Leave a Comment