Cartoon space rocket flying in the stars

Creating a custom Drush command in Drupal 8 (Drush 9+)

Tan Nguyen

|

In Drupal 8.4.X and later releases, Drush 9+ is the recommended version.
You can check more detail in https://www.drush.org/latest/install/#drupal-compatibility

I. Create a custom module, define custom Drush commands.

We will need create a custom module, structured like this:

create custom drush commands

1. drush_command_example.info file.

name: Drush Command Example
description: Provides examples for creating custom Drush commands.
core: 8.x
core_version_requirement: ^8 || ^9
type: module
package: Examples

The core_version_requirement: key specifies that the module is compatible with all versions of Drupal 8 and 9 and the core: key is required here because Drupal Core versions before 8.7.7 do not recognize core_version_requirement key.

2. drush.services.yml file.

services:
  drush_command_example.commands:
    class: \Drupal\drush_command_example\Commands\CustomCommands
    tags:
      - { name: drush.command }

3. CustomCommands.php file.

<?php
namespace Drupal\drush_command_example\Commands;

use Drush\Commands\DrushCommands;


/**
 * Drush command file.
 */
class CustomCommands extends DrushCommands {

  /**
   * A custom Drush command to displays the given text.
   * 
   * @command drush-command-example:print-me
   * @param $text Argument with text to be printed
   * @option uppercase Uppercase the text
   * @aliases ccepm,cce-print-me
   */
  public function printMe($text = 'Hello world!', $options = ['uppercase' => FALSE]) {
    if ($options['uppercase']) {
      $text = strtoupper($text);
    }
    $this->output()->writeln($text);
  }
}

II. Enable drush_command_example module and test command.

Enable custom drush example module

drush list

drush list command to show custom drush command

Now we can use our custom Drush command we just created.

check custom drush command

Test custom Drush command

drush ccepm --help

drush drush-command-example:print-me "We are Lilengine"
drush drush-command-example:print-me "We are Lilengine" --uppercase

drush ccepm "We are Lilengine"
drush ccepm "We are Lilengine" --uppercase

drush cce-print-me "We are Lilengine"
drush cce-print-me "We are Lilengine" --uppercase

 

Add new comment

The content of this field is kept private and will not be shown publicly.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.

Comments

  • Allowed HTML tags: <em> <strong> <cite> <blockquote cite> <ul type> <ol start type> <li> <dl> <dt> <dd> <p>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
  • Use [gist:#####] where ##### is your gist number to embed the gist
    You may also include a specific file within a multi-file gist with [gist:####:my_file].

Spread the word