Drupal: Drush

by Gisle Hannemyr

The Drupal shell (drush) is a very useful tool that is used via the CLI to help with administrative taks for a Drupal website.

Table of contents

https://drupalize.me/topic/drush

Introduction

To help with adminsitration of a Drupal site, there exists a Gnu/Linux command line shell and scripting interface for Drupal named drush – the Drupal shell.

For installation instructions, please see the section Install drush in the chapter about installing Drupal.

Basic usage

Drush just types out a list of the most used commands if you start it without any arguments. Drush also provides an extensive help system that describes both drush commands and topics of general interest. Try the following three commands to learn more about what drush can do. The first shows a list of all drush commands. The next to shows menus that let you dig deeper into the built-in help system.

$ drush
$ drush help --filter
$ drush topic

You may also supply of a command as an argument to help. Example:

$ drush help rebuild

The drush core comes with lots of useful commands for interacting with code like modules, themes and profiles. It can also be used to update the configuration, execute SQL queries, migrate databases, and to executes miscellanious commands, such as running cron or clearing the cache.

In this section I shall list the most useful commands to give you an idea about what drush can do.

See alsoFor a longer list of drush commands, visit Peter Brady's website Drush Commands. This is a search­able reference are the core Drush commands for Drush versions 6, 7, 8 and 9 – as well as the major contributed modules that declare their own Drush commands (Views, Features, Devel, Display Suite etc.). There is also online documentation at Drush.org.

Here is how to display what version of the Drupal core drush you're running.

$ drush core-status --fields=drupal-version,drush-version
Drupal version : 10.1.5   
Drush version  : 12.3.0.0 

For most drush commands, you need to be in or below your webroot when invoking drush. Otherwise drush does not know how to locate your Drupal settings file, etc. Assuming that your webroot is /var/www/html, here is a command that gives an overview over your Drupal installation:

$ cd /var/www/html
$ drush status
Drupal version : 10.1.5 
…

On a multisite, drush will act on the default site, unless you use the @sites to make the following command apply to all sites. To apply the command to a single site that is part of a multisite, position yourself in the directory holding the settings.php of the site.

Many drush commands come in two versions – long and short. They are equivalent. For instance, to show a list of recent log entries (watchdog messages), you may use one of the following two commands:

$ drush watchdog-show
$ drush ws

This may be helpful when the site only is able to show a blank page (WSOD).

To delete all watchdog messages:

$ drush wd-del all

Clearing, updating and rebuilding

If you have changed something in the front-end, and the change is not visible on the site, rebuilding all the caches often help:

$ drush rebuild
$ drush cr

Actually, not all caches are flushed. To flush all (or some) of the caches holding preset image styles, do:

$ drush image-flush
$ drush if

To run drupal-cron from the CLI, do:

$ drush cron

The pm:update command has been deprecated, You should update your Drupal project with composer. However, that does not take care of any database updates that may be required after updating the codebase. To explicitly run the database update script, use this command:

$ drush updb

The following command will run the database update script on all the sites in the multisite.

$ drush @sites updb

The Drupal registry is a list of PHP classes and the files they go with. If you move or rename a component, you may break the registry so bad that Drupal is unable to boostrap. Such problems cannot be repaired with the regular cache rebuild because some class is required when the system is trying to bootstrap.

$ drush registry-rebuild --fire-bazooka
$ drush rr --no-cache clear

noteThis does not work for drush version 8 yet. The error message is: “Error! Registry Rebuild requires a working Drupal site to operate on.” This issue: Registry Rebuild Drupal 8 support must be fixed to for the drush registry-rebuild command to work. There also should be a registry_rebuild-8.x branch.

If drush don't recognise registry-rebuild, you may need to download it first. Likewise, to update to the latest version:

$ drush @none dl registry_rebuild-7.x

That will make drush download it into the .drush folder in your home directory.

Interacting with extensions

Drush used to be able to download extensions. Please note that composer is the canonical method for downloading a Drupal extension (since Drupal 8.8). It will resolve all external dependencies that is listed in the project's composer.json file. To learn how to download with drush, see the Drupal 7 version of this chapter.

You may still use drush to enable, disable and list extensions,

Modules

After downloading a module with composer you may use these pair of commands to enable or uninstall projects:

$ drush en -y list
$ drush pmu -y list

You can use the * wildcard at the end of a name.

To see a list of all non-core enabled modules, and the version that is installed, use one of the following commands:

$ drush pm-list --no-core --status=enabled
$ drush pml --no-core --status=enabled
$ drush pml --type=module --status=enabled
$ drush @sites pml --no-core --status=enabled -y

DSE: List of all active modules used in a site

The first two are just the long and short version of the same command. The third will do a full inventory of all enabled modules on a multi-site.

Themes

List themes:

$ drush pml --type=theme

Installing and uninstalling:

drush theme:uninstall THEME_MACHINE_NAME
drush theme:enable THEME_MACHINE_NAME
drush config-set system.theme default THEME_MACHINE_NAME

DSE: How can I change theme?.

Manipulating users

To get information about user #1 using drush ver. 11:

$ drush uinf --uid=1
+---------+---------------+-----------------------------+---------------+-------------+
| User ID | User name     | User mail                   | User roles    | User status |
+---------+---------------+-----------------------------+---------------+-------------+
| 1       | superadmin    | bob@example.com             | authenticated | 1           |
|         |               |                             | administrator |             |
+---------+---------------+-----------------------------+---------------+-------------+

To reset the password for user superadmin:

$ drush upwd superadmin password

To create a new user:

$ drush user-create username --password="password"
$ drush ucrt username --password="password"
$ drush ucrt bob --password="secret"

To add a role to a list of specified user accounts, use:

$ drush user-add-role role user-list
$ drush urol role user-list
$ drush urol editor bob,ed

To remove some PII (currently the email address and password) from the datebase before moving a production database to an outside contractor or a staging server, there is sql-sanitize/sqlsan. The pattern for the email replacement in the sanitization operation may contain the following replacement patterns: %uid, %mail or %name. Using the argument “no” disables the santizen action. Examples:

$ drush sql-sanitize --sanitize-email=no  --sanitize-password=no
$ drush sqlsan --sanitize-email=u%uid@localhost  --sanitize-password=pw

The first command will do nothing. The second command will change all email-addresses to “u1234@localhost” (where the number is the uid) and the password for all users to “pw”.

noteThis command changes these fields directly in the database. Never run it on a production site.
It may not be fully GDPR compliant. The database may contain other fields with PII, such as user names and phone numbers.

To list all users on the website, use drush to execute this SQL query:

$ drush sql-query "SELECT uid, name FROM users_field_data;"
0
1       superadmin
3	Jane
2	Bob

tipThere is also this package that you can install with composer to get a shorter command list all users: richardbporter/drush-users-commands. After it has been installed, you can use this command:
$ drush user-list

You can use drush to generate a one time log in link for any user. To do this for user #1, use this command:

$ drush uli --uid=1 --no-browser
http://default/user/reset/1/1646038835/5w99q0cTfEnImwMaHpLMuf1Qjg4iRiZVOs/login

Use the --no-browser-option if you're logged in on a server where no browser is installed. Transform it into an URL for the actual domain like this:

https://example.com/user/reset/1/1646038835/5w99q0cTfEnImwMaHpLMuf1Qjg4iRiZVOs/login

And copypaste the URL into the browser's address field to log in.

Generate boilerplate files

Drush may be used to generate boilerplate files for modules, plugins, services, etc. To see what's available, type:

$ drush generate

Examples:

$ drush generate readme
$ drush generate controller

Drush asks questions so that the generated code is as polished as possible. After generating, Drush lists the files that were created.

Other useful drush commands

To execute PHP-code (including calling PHP functions, do:

$ drush php-eval "drupal_flush_all_caches();"
$ drush eval "drupal_flush_all_caches();"

Source DSE: How to execute php script using drush?

To execute SQL queries do:

$ drush sql-query "DELETE FROM key_value WHERE COLLECTION='update_fetch_task'"

This fixes a quirk when Drupal is unuable to update, reporting "No available releases found". This is because of junk left behind in the {key_value} table. Deleting with the above drush command fixes the problem.

Source DSE: Cannot update: "No available releases found".

To see a list of all the variables that is defined for a specific site, use vget. Similarly, you can use vset to set a variable or to change an existing variable to a different value. To delete a variable, there is vdel. Examples:

$ drush config-set mymodule.settings mymodule_foobar 1
$ drush cr
$ drush config-get mymodule.settings > variables.txt
$ drush config-get mymodule.settings mymodule_foobar
'mymodule.settings:mymodule_foobar': '1'
$ drush config-delete mymodule.settings mymodule_foobar
$ drush config-get mymodule.settings mymodule_foobar
No matching key found in mymodule.settings config.

For instance, to inspect the system.site configuration and set system.site:page.front to /node, using drush:

$ drush config-set system.site
uuid: c008cbe0-6acd-44c4-8e87-ccbd19a3d02a
name: 'My site'
mail: admin@example.com
slogan: ''
page:
  403: ''
  404: ''
  front: /node/42
admin_compact_mode: false
weight_select_max: 100
langcode: en
default_langcode: en
_core:
  default_config_hash: yZadRE77Va-G6dxhd2kPYapAvbnSvTF6hO4oZiOEynI
mail_notification: ''
$ drush config-set system.site page.front /node

Here is a handy pair of commands to get and set the variable file_public_path when converting a sub-site of a Drupal multi-site to a single site.

$ drush vget file_public_path
file_public_path: sites/example.com/files
$ drush vset file_public_path sites/default/files

Troubleshooting

Sometimes after a botched composer command, drush stops working. The typical symptom is that drush responds “The drush command X could not be found” for every X, including cr and version, or that you get an error like this: “sh: 0: getcwd() failed. No such file or directory.” The following two commands usually fixes this condition: [D8?]

$ drush cr # outside the webroot directory
$ drush cr # inside the webroot directory

If you get this error on a site that has dependencies managed by composer and there is no “drush” directory in “vendor”:

$ drush status
Error: Call to undefined method Twig\Extension\CoreExtension::getName() in …

Add the correct version of drush to the project. In the project directory:

$ composer require 'drush/drush'

Final word

Special uses of Drush is also discussed elsewhere in the ebook. The relevant links are these:


Last update: 2018-01-30 [gh].