How to create custom Drush command in Drupal
In this tutorial se are going learn how to create custom Drush command in drupal. For that we need to create a custom module. The file structure will be like below
drush_command_example Commands CustomCommands.php drush_command_example.info drush.services.yml
1. drush_command_example.info file
name: Drush Command Example
description: This is our custom drush command.
core: 8.x
core_version_requirement: ^8 || ^9
type: module
package: ttn
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 ttndrush,tthndrush-print-me
*/
public function printMe($text = 'Hello world!', $options = ['uppercase' => FALSE]) {
if ($options['uppercase']) {
$text = strtoupper($text);
}
$this->output()->writeln($text);
}
}
Enable module or if you created drush command in existing module than please clear cache. you can see custom drush command in list using
drush list
We can use our newly created drush command as below.
drush ttndrush --help
drush ttndrush "hello from to the new"
drush ttndrush "hello from to the new" --uppercase
drush ttndrush-print-me "hello from to the new"
drush ttndrush-print-me "hello from to the new" --uppercase