Backend and Infrastructure

Add Options to a Custom Drush Command for Drupal 8, 9, 10, and 11

When you create a custom Drush command it might be useful to allow users to pass options (predefined values) that change the way a command works. You can think of options as being flags, or variables, that affect the command's internal logic. As an example, consider the Drush core user:login command which by default returns a one-time login link for the root account. The command also accepts an optional --name option which allows the internal logic to create a link for a specified user instead of only being able to create links for the root user. This makes the command useful in a wider variety of situations. Another common option is the --format option which allows a user to specify that they want the command to return its output in a format (CSV, JSON, Table, etc.) other than the default.

Options are defined in the Drush command's attributes. Their values are passed as part of an associative array to the command method. Unlike parameters, options are not ordered, so you can specify them in any order, and they are called with two dashes like --my-option. Options are always optional, not required, and can be set up to accept a value --name=John or as a boolean flag without a value --translate.

In this tutorial we'll:

  • Declare options for a custom Drush command in its attributes
  • Learn how to use these options inside the custom Drush command method

By the end of this tutorial, you should be able to add options to your own custom Drush commands.

Command Line Tools for Drupal