• No results found

Drush Documentation. Release 7.0.0

N/A
N/A
Protected

Academic year: 2021

Share "Drush Documentation. Release 7.0.0"

Copied!
29
0
0

Loading.... (view fulltext now)

Full text

(1)

Release 7.0.0

Maintained by Moshe Weitzman with much help from Owen Barton, greg.1.anderson, jonhattan, Mark Sonnabaum, and Jonathan Hedstrom

(2)
(3)

1 Overview 1 1.1 Description . . . 1 1.2 Drush Versions . . . 1 1.3 Usage . . . 1 1.4 Support . . . 2 1.5 Misc . . . 2 1.6 Requirements. . . 2 1.7 Install - Composer . . . 2 1.8 Install - PEAR . . . 3 1.9 Install - Manual. . . 3 1.10 Post-install . . . 4

1.11 Additional configurations for MAMP . . . 4

1.12 Additional configurations for other AMP stacks. . . 5

1.13 Running a Specific PHP for Drush . . . 5

1.14 Configuring php.ini. . . 6

1.15 Configuring Drush for PHP 5.5 . . . 7

1.16 Installing Drush on Windows . . . 7

1.17 Options . . . 8

1.18 Drush Configuration Files . . . 8

1.19 drushrc.php . . . 8

1.20 Site aliases . . . 9

1.21 Commands . . . 9

1.22 Credits . . . 10

2 User Guide 11 2.1 Remote Operations on Drupal Sites via a Bastion Server . . . 11

2.2 The Drush Bootstrap Process . . . 12

2.3 Creating Custom Drush Commands . . . 14

2.4 Drush Contexts . . . 18

2.5 Running Drupal cron tasks from drush . . . 19

2.6 Drush Shell Aliases . . . 20

2.7 Drush Shell Scripts . . . 21

2.8 Strict Option Handling . . . 22

3 Indices and tables 25

(4)
(5)

Overview

1.1 Description

Drush is a command line shell and Unix scripting interface for Drupal. If you are unfamiliar with shell scripting, reviewing the documentation for your shell (e.g. man bash) or reading an online tutorial (e.g. search for “bash tutorial”) will help you get the most out of Drush.

Drush core ships with lots of useful commands for interacting with code like modules/themes/profiles. Similarly, it runs update.php, executes sql queries and DB migrations, and misc utilities like run cron or clear cache.

1.2 Drush Versions

Each version of Drush supports multiple Drupal versions. Drush 6 is recommended version. Drush Version Branch PHP Compatible Drupal versions Code Status Drush 7 master 5.3.0+ D6, D7, D8

Drush 6 6.x 5.3.0+ D6, D7 Drush 5 5.x 5.2.0+ D6, D7

Drush 4 4.x 5.2.0+ D5, D6, D7 Unsupported

Drush 3 3.x 5.2.0+ D5, D6 Unsupported

Drush comes with a full test suite powered byPHPUnit. Each commit gets tested by the awesomeTravis.ci continuous integration service.

1.3 Usage

Drush can be run in your shell by typing “drush” from within any Drupal root directory. $ drush [options] <command> [argument1] [argument2]

Use the ‘help’ command to get a list of available options and commands: $ drush help

For even more documentation, use the ‘topic’ command: $ drush topic

Installation instructions can be found below. For a full list of Drush commands and documentation by version, visit

http://www.drush.org.

(6)

1.4 Support

Please take a moment to review the rest of the information in this file before pursuing one of the support options below. • Post support requests toDrupal Answers.

• Bug reports and feature requests should be reported in theGitHub Drush Issue Queue. • Use pull requests (PRs) to contribute to Drush. See /CONTRIBUTING.md.

• It is still possible to search the old issue queue on Drupal.org forfixed bugs,unmigrated issues,unmigrated bugs, and so on.

1.5 Misc

• www.drush.org

• Subscribe tohttps://github.com/drush-ops/drush/releases.atomto receive notification on new releases. • A list of modules that include Drush integration

• For more information, please see theResources and theDrush FAQ. Run thedrush topiccommand for even more help.

• If you are using Debian or Ubuntu, you can alternatively use the Debian packages uploaded in your distribution. You may need to use the backports to get the latest version, if you are running a LTS or “stable” release. • For advice on using Drush with your ISP, see the hosting section of the Resources page on drush.org.

1.6 Requirements

• Drush commands that work with git require git 1.7 or greater. • Drush works best on a Unix-like OS (Linux, OS X)

• Most Drush commands run on Windows. See INSTALLING DRUSH ON WINDOWS, below.

1.7 Install - Composer

• Install Composer globally(if needed).

• Make sure Composer’s global bin directory is on the system PATH (recommended): echo ’export PATH=$HOME/.composer/vendor/bin:$PATH’ >> $HOME/.bashrc • To install Drush 6.x (stable), runcomposer global require drush/drush:6.* Some alternate commands in case you want some other variant of Drush:

composer global require drush/drush:6.1.0

# Master branch as a git clone. Great for contributing back to Drush project. composer global require drush/drush:dev-master --prefer-source

(7)

1.8 Install - PEAR

If you have trouble with PEAR installation, consider trying MANUAL INSTALLATION. It is not too hard. pear channel-discover pear.drush.org

pear install drush/drush

Tip: Use sudo to overcome permission problems. If the channel-discover fails, try running the following sequence of commands:

pear upgrade --force Console_Getopt pear upgrade --force pear

pear upgrade-all

To update, runpear upgrade drush/drush

To get alternate drush versions, replace that last line with one of the below that matches your fancy. pear install drush/drush-5.0.0

pear install drush/drush-6.0.0RC4

See the POST-INSTALL section for configuration tips.

1.9 Install - Manual

1. Place the uncompressed drush.tar.gz, drush.zip, or cloned git repository in a directory that is outside of your web root.

2. Make the ‘drush’ command executable: $ chmod u+x /path/to/drush/drush

3. Configure your system to recognize where Drush resides. There are 3 options:

(a) Create a symbolic link to the Drush executable in a directory that is already in your PATH, e.g.: $ ln -s /path/to/drush/drush /usr/bin/drush

(b) Explicitly add the Drush executable to the PATH variable which is defined in the the shell configuration file called .profile, .bash_profile, .bash_aliases, or .bashrc that is located in your home folder, i.e.:

export PATH="$PATH:/path/to/drush:/usr/local/bin" Your system will search path options from left to right until it finds a result.

(a) Add an alias for drush (this method can also be handy if you want to use 2 versions of Drush, for example Drush 5 or 6 (stable) for Drupal 7 development, and Drush 7 (master) for Drupal 8 development).

To add an alias to your Drush 7 executable, add this to you shell

configuration file (see list in previous option): $ alias drush-master=/path/to/drush/drush For options 2 and 3 above, in order to apply your changes to your current session, either log out and then log back in again, or re-load your bash configuration file, i.e.:

$ source .bashrc

NOTE: If you do not follow this step, you will need to inconveniently run Drush commands using the full path to the executable “/path/to/drush/drush” or by navigating to /path/to/drush and running ”./drush”. The -r or -l options will be required (see USAGE, below).

(8)

4. Test that Drush is found by your system: $ which drush

See the POST-INSTALL section for configuration tips.

1.10 Post-install

1. See example.bashrc for instructions

on how to add some | useful shell aliases that provides even tighter integration between | drush and bash. You may source this file directly into your shell by adding to | your .bashrc (or equivalent): source /path/to/drush/examples/example.bashrc

2. If you didn’t source it the step above, see top of

drush.complete.sh file for instructions adding bash completion for

drush | command to your shell. Once configured, completion works for site aliases, | command names, shell aliases, global options, and command-specific options.

3. Optional. If drush.complete.sh is being sourced (ideally in

bash_completion.d), you can use the supplied**drush*ps1() sh

function to add your current drush site (set withdrush use @sitename) to your PS1 prompt like so:

bash if [ "\$(type -t __git_ps1)" ] && [ "\$(type -t __drush_ps1)" ]; then PS1=’\u@\h \w$(__git_ps1 " (%s)")$(__drush_ps1 "[%s]")\$ ’ fi Putting this in a .bashrc/.bash*profile/.profile would produce

this prompt:

msonnabaum@hostname ~/repos/drush (master)[@sitename]$

4. Help the Drush development team by sending anonymized usage statistics. To automatically send usage data, please add the following to a .drushrc.php file:

php $options[’drush_usage_log’] = TRUE; $options[’drush_usage_send’] = TRUE;

Stats are usually logged locally and sent whenever log file exceeds

50Kb. | Alternatively, one may disable automatic sending and instead use |usage-showandusage-send commands to more carefully send data.

1.11 Additional configurations for MAMP

Users of MAMP will need to manually specify in their PATH which

version of php | and MySQL to use in the command line interface. This is independent of the php | version selected in the MAMP application settings. Under OS X, edit (or create | if it does not already exist) a file called .bash_profile in your home folder.

(9)

export PATH="/Applications/MAMP/Library/bin:/Applications/MAMP/bin/php5.3/bin:$PATH" If you want to use php 5.4.x, add this line instead:

export PATH="/Applications/MAMP/Library/bin:/Applications/MAMP/bin/php5.4/bin:$PATH"

If you have MAMP v.1.84 or lower, this configuration will work for

both version | of PHP:

export PATH="/Applications/MAMP/Library/bin:/Applications/MAMP/bin/php5/bin:$PATH"

If you have done this and are still getting a “no such file or

directory” error | from PDO::__construct, try this: sudo mkdir /var/mysql

sudo ln -s /Applications/MAMP/tmp/mysql/mysql.sock /var/mysql/mysql.sock

Additionally, you may need to adjust your php.ini settings before you

can use | drush successfully. See CONFIGURING PHP.INI below for more details on how to | proceed.

1.12 Additional configurations for other AMP stacks

Users of other Apache distributions such as XAMPP, or Acquia’s Dev

Desktop will | want to ensure that its php can be found by the command line by adding it to | the PATH variable, using the method in 3.b above. Depending on the version and | distribution of your AMP stack, PHP might reside at:

Path Application

/Applications/acquia-drupal/php/bin Acquia Dev Desktop (Mac) /Applications/xampp/xamppfiles/bin XAMP (Mac)

/opt/lampp/bin XAMPP (Windows)

Additionally, you may need to adjust your php.ini settings before you

can use | drush successfully. See CONFIGURING PHP.INI below for more details on how to | proceed.

1.13 Running a Specific PHP for Drush

If you want to run Drush with a specific version of php, rather than
(10)

the | php defined by your shell, you can add an environment variable to your | the shell configuration file called .profile, .bash_profile, .bash_aliases, | or .bashrc that is located in your home folder:

export DRUSH_PHP=’/path/to/php’

1.14 Configuring php.ini

Usually, php is configured to use separate php.ini files for the web

server and | the command line. Make sure that Drush’s php.ini is given as much memory to | work with as the web server is; otherwise, Drupal might run out of memory when | Drush bootstraps it.

To see which php.ini file Drush is using, run: $ drush status

To see which php.ini file the webserver is using, use the phpinfo()

function in | a .php web page. Seehttp://drupal.org/node/207036.

If Drush is using the same php.ini file as the web server, you can

create a | php.ini file exclusively for Drush by copying your web server’s php.ini file to | the folder $HOME/.drush or the folder /etc/drush. Then you may edit this file | and change the settings described above without affecting the php enviornment | of your web server.

Alternately, if you only want to override a few values, copy

example.drush.ini | from the /examples folder into $HOME/.drush or the folder /etc/drush and edit | to suit. See comments in example.drush.ini for more details.

You may also use environment variables to control the php settings

that Drush | will use. There are three options: export PHP_INI=’/path/to/php.ini’ export DRUSH_INI=’/path/to/drush.ini’ export PHP_OPTIONS=’-d memory_limit="128M"’

(11)

specify the | full path to a php.ini or drush.ini file, should you wish to use one that is | not in one of the standard locations described above. The PHP_OPTIONS | environment variable can be used to specify individual options that should | be passed to php on the command line when Drush is executed.

Drush requires a fairly unrestricted php environment to run in. In

particular, | you should insure that safe_mode, open_basedir, disable_functions and | disable_classes are empty. If you are using php 5.3.x, you may also need to | add the following definitions to your php.ini file:

magic_quotes_gpc = Off magic_quotes_runtime = Off magic_quotes_sybase = Off

1.15 Configuring Drush for PHP 5.5

If you are running on Linux, you may find that you need the php5-json package. On Ubuntu, you can install it via:

apt-get install php5-json

1.16 Installing Drush on Windows

Windows support has improved, but is still lagging. For full

functionality, | consider using on Linux/Unix/OSX using Virtualbox or other virtual machine.

There is a Windows msi installer for drush available athttp://www.drush.org/drush_windows_installer. Please see that page for more information on running Drush on Windows.

Whenever the documentation or the help text refers to ‘drush [option] ‘ or something similar, ‘drush’ may need to be replaced by

‘drush.bat’.

Additional Drush Windows installation documentation can be found at

http://drupal.org/node/594744.

Most Drush commands will run in a Windows CMD shell or PowerShell, but

the | Git Bash shell provided by the ‘Git for Windows’ installation is the preferred | shell in which to run Drush commands. For more information on “Git for Windows’ | visithttp://msysgit.github.com/.

(12)

When creating aliases for Windows remote machines, pay particular

attention to | information presented in the example.aliases.drushrc.php file, especially when | setting values for ‘remote-host’ and ‘os’, as these are very important when | running Drush rsync and Drush sql-sync commands.

1.17 Options

For multisite installations, use the -l option to target a particular

site. If | you are outside the Drupal web root, you might need to use the -r, -l or other | command line options just for Drush to work. If you do not specify a URI with | -l and Drush falls back to the default site configuration, Drupal’s | $GLOBAL[’base_url’] will be set tohttp://default. This may cause some | functionality to not work as expected. $ drush -l http://example.com pm-update

Related Options:

-r <path>, --root=<path> Drupal root directory to use (defaults to current directory or anywhere in a Drupal directory tree) -l <uri> , --uri=<uri> URI of the Drupal site to use -v, --verbose Display verbose output.

Very intensive scripts can exhaust your available PHP memory. One

remedy is to | just restart automatically using bash. For example: while true; do drush search-index; sleep 5; done

1.18 Drush Configuration Files

Inside the examples directory you will find some example files to help

you get | started with your Drush configuration file (example.drushrc.php), site alias | definitions (exam-ple.aliases.drushrc.php) and Drush commands | (sandwich.drush.inc). You will also see an example ‘policy’ file which can be | customized to block certain commands or arguments as required by your | organization’s needs.

1.19 drushrc.php

(13)

in a | drushrc.php file. Multiple Drush configuration files can provide the | flexibility of providing specific options in different site directories of a | multi-site installation. See example.drushrc.php for examples and installation | details.

1.20 Site aliases

Drush lets you run commands on a remote server, or even on a set of

remote | servers. Once defined, aliases can be references with the @ nomenclature, i.e. # Synchronize staging files to production

$ drush rsync @staging:%files/ @live:%files

# Syncronize database from production to dev, excluding the cache table $ drush sql-sync --structure-tables-key=custom --no-cache @live @dev

Seehttp://drupal.org/node/670460and

example.aliases.drushrc.php for more | information.

1.21 Commands

Drush can be extended to run your own commands. Writing a Drush command is no harder than writing simple Drupal modules, since they both follow the same structure.

See sandwich.drush.inc for a quick tutorial on Drush command files. Otherwise, the core commands in Drush are good models for your own commands.

You can put your Drush command file in a number of places:

1. In a folder specified with the –include option (seedrush topic docs-configuration). 2. Along with one of your enabled modules. If your command is related to an

existing module, this is the preferred approach.

3. In a .drush folder in your HOME folder. Note, that you have to create the .drush folder yourself.

4. In the system-wide Drush commands folder, e.g. /usr/share/drush/commands. 5. In Drupal’s /drush or sites/all/drush folders. Note, that you have to create the

drush folder yourself.

In any case, it is important that you end the filename with ”.drush.inc”, so that Drush can find it. Frequently Asked Questions —

Q: What does "drush" stand for? A: The Drupal Shell.

Q: How do I pronounce Drush?

A: Some people pronounce the dru with a long u like Drupal. Fidelity points go to them, but they are in the minority. Most pronounce Drush so that it rhymes with hush, rush, flush, etc. This is the preferred pronunciation.

(14)

Q: Does Drush have unit tests?

A: Drush has an excellent suite of unit tests. See the README.md file in the /tests subdirectory for more information.

1.22 Credits

• Originally developed byArto Bendikenfor Drupal 4.7. • Redesigned byFranz Heinzmannin May 2007 for Drupal 5. • Maintained byMoshe Weitzmanwith much help from

Owen Barton, greg.1.anderson, jonhattan, Mark Sonnabaum, and Jonathan Hedstrom.

(15)

User Guide

2.1 Remote Operations on Drupal Sites via a Bastion Server

Wikipedia defines abastion serveras “a special purpose computer on a network specifically designed and configured to withstand attacks.” For the purposes of this documentation, though, any server that you can ssh through to reach other servers will do. Using standard ssh and drush techniques, it is possible to make a two-hop remote command look and act as if the destination machine is on the same network as the source machine.

2.1.1 Recap of Remote Site Aliases

Site aliases can refer to Drupal sites that are running on remote machines simply including host’ and ‘remote-user’ attributes: $aliases[’internal’] = array( ’remote-host’ => ’internal.company.com’, ’remote-user’ => ’wwwadmin’, ’uri’ => ’http://internal.company.com’, ’root’ => ’/path/to/remote/drupal/root’, );

With this alias defintion, you may use commands such as ‘drush @internal status‘, ‘drush ssh @internal‘ and ‘drush rsync @internal @dev‘ to operate remotely on the internal machine. What if you cannot reach the server that site is on from your current network? Enter the bastion server.

2.1.2 Setting up a Bastion server in .ssh/config

If you have access to a server, bastion.company.com, which you can ssh to from the open internet, and if the bastion server can in turn reach the internal server, then it is possible to configure ssh to route all traffic to the internal server through the bastion. The .ssh configuratin file would look something like this:

In.ssh/config:

Host internal.company.com

ProxyCommand ssh [email protected] nc %h %p

That is all that is necessary; however, if the dev machine you are configuring is a laptop that might sometimes be inside the company intranet, you might want to optimize this setup so that the bastion is not used when the internal server can be reached directly. You could do this by changing the contents of your .ssh/config file when your network settings change – or you could use drush.

(16)

2.1.3 Setting up a Bastion server via drush configuration

First, make sure that you do not have any configuration options for the internal machine in your .ssh/config file. The next step after that is to identify when you are connected to your company intranet. I like to determine this by using the ‘route‘ command to find my network gateway address, since this is always the same on my intranet, and unlikely to be encountered in other places.

Indrushrc.php:

# Figure out if we are inside our company intranet by testing our gateway address against a known value exec("route -n | grep ’^0\.0\.0\.0’ | awk ’{ print $2; }’ 2> /dev/null", $output);

if ($output[0] == ’172.30.10.1’) {

drush_set_context(’MY_INTRANET’, TRUE); }

After this code runs, the ‘MY_INTRANET’ context will be set if our gateway IP address matches the expected value, and unset otherwise. We can make use of this in our alias files.

Inaliases.drushrc.php:

if (drush_get_context(’MY_INTRANET’, FALSE) === FALSE) { $aliases[’intranet-proxy’] = array(

’ssh-options’ => ’ -o "ProxyCommand ssh [email protected] nc %h %p"’, ); } $aliases[’internal-server’] = array( ’parent’ => ’@intranet-proxy’, ’remote-host’ => ’internal.company.com’, ’remote-user’ => ’wwwadmin’, ); $aliases[’internal’] = array( ’parent’ => ’@internal-server’, ’uri’ => ’http://internal.company.com’, ’root’ => ’/path/to/remote/drupal/root’, );

The ‘parent’ term of the internal-server alias record is ignored if the alias it references (‘@intranet-proxy‘) is not defined; the result is that ‘ssh-options’ will only be defined when outside of the intranet, and the ssh ProxyCommand to the bastion server will only be included when it is needed.

With this setup, you will be able to use your site alias‘@internal‘ to remotely operate on your internal intranet Drupal site seemlessly, regardless of your location – a handy trick indeed.

2.2 The Drush Bootstrap Process

When preparing to run a command, drush works by “bootstrapping” the Drupal environment in very much the same way that is done during a normal page request from the web server, so most drush commands run in the context of a fully-initialized website.

For efficiency and convenience, some drush commands can work without first bootstrapping a Drupal site, or by only partially bootstrapping a site. This is more efficient, because there is sometimes a slight delay involved with bootstrapping, especially in some of the later stages. It is also a matter of convenience, because some commands are useful to use even when you do not have a working Drupal site available to bootstrap. For example, you can use drush to download Drupal with ‘drush dl drupal‘. This obviously does not require any bootstrapping to work.

Starting with Drush-5, the loading of configuration files is no longer closely tied to the drush bootstrapping process. All configuration files are now loaded upfront, during DRUSH_BOOTSTRAP_DRUSH, with the Drupal root and site

(17)

configuration files being loaded in advance of the corresponding bootstrap phase. See ‘drush topic docs-configuration‘ for details on drush configuration files.

2.2.1 DRUSH_BOOTSTRAP_DRUSH

Only bootstrap Drush, without any Drupal specific code.

Any code that operates on the Drush installation, and not specifically any Drupal directory, should bootstrap to this phase.

2.2.2 DRUSH_BOOTSTRAP_DRUPAL_ROOT

Set up and test for a valid drupal root, either through the -r/–root options, or evaluated based on the current working directory.

Any code that interacts with an entire Drupal installation, and not a specific site on the Drupal installation should use this bootstrap phase.

2.2.3 DRUSH_BOOTSTRAP_DRUPAL_SITE

Set up a Drupal site directory and the correct environment variables to allow Drupal to find the configuration file. If no site is specified with the -l / –uri options, Drush will assume the site is ‘default’, which mimics Drupal’s behaviour. If you want to avoid this behaviour, it is recommended that you use the DRUSH_BOOTSTRAP_DRUPAL_ROOT bootstrap phase instead.

Any code that needs to modify or interact with a specific Drupal site’s settings.php file should bootstrap to this phase.

2.2.4 DRUSH_BOOTSTRAP_DRUPAL_CONFIGURATION

Load the settings from the Drupal sites directory.

This phase is analagous to the DRUPAL_BOOTSTRAP_CONFIGURATION bootstrap phase in Drupal itself, and this is also the first step where Drupal specific code is included.

This phase is commonly used for code that interacts with the Drupal install API, as both install.php and update.php start at this phase.

2.2.5 DRUSH_BOOTSTRAP_DRUPAL_DATABASE

Connect to the Drupal database using the database credentials loaded during the previous bootstrap phase. This phase is analogous to the DRUPAL_BOOTSTRAP_DATABASE bootstrap phase in Drupal.

Any code that needs to interact with the Drupal database API needs to be bootstrapped to at least this phase.

2.2.6 DRUSH_BOOTSTRAP_DRUPAL_FULL

Fully initialize Drupal.

This is analogous to the DRUPAL_BOOTSTRAP_FULL bootstrap phase in Drupal. Any code that interacts with the general Drupal API should be bootstrapped to this phase.

(18)

2.2.7 DRUSH_BOOTSTRAP_DRUPAL_LOGIN

Log in to the initialiased Drupal site.

This bootstrap phase is used after the site has been fully bootstrapped. This is the default bootstrap phase all commands will try to reach, unless otherwise specified.

This phase will log you in to the drupal site with the username or user ID specified by the –user/ -u option.

Use this bootstrap phase for your command if you need to have access to information for a specific user, such as listing nodes that might be different based on who is logged in.

2.2.8 DRUSH_BOOTSTRAP_MAX

This is not an actual bootstrap phase. Commands that use DRUSH_BOOTSTRAP_MAX will cause drush to bootstrap as far as possible, and then run the command regardless of the bootstrap phase that was reached. This is useful for drush commands that work without a bootstrapped site, but that provide additional information or capabilities in the presence of a bootstrapped site. For example, ‘drush pm-releases modulename‘ works without a bootstrapped Drupal site, but will include the version number for the installed module if a Drupal site has been bootstrapped.

2.3 Creating Custom Drush Commands

Creating a new drush command is very easy. There are four simple steps.

1. Create a command file called COMMANDFILE.drush.inc 2. Implement the function COMMANDFILE_drush_command()

3. Implement the functions that your commands will call. These will usually be named drush_COMMANDFILE_COMMANDNAME().

For an example drush command, see examples/sandwich.drush.inc. The steps for implementing your command are explained in more detail below.

2.3.1 Create COMMANDFILE.drush.inc

The name of your drush command is very important. It must end in ”.drush.inc” to be recognized as a drush command. The part of the filename that comes before the ”.drush.inc” becomes the name of the commandfile. Optionally, the commandfile may be restricted to a particular version of Drupal by adding a ”.dVERSION” after the name of the commandfile (e.g. ”.d8.drush.inc”) Your commandfile name is used by drush to compose the names of the functions it will call, so choose wisely.

The example drush command, ‘make-me-a-sandwich’, is stored in the ‘sandwich’ commandfile, ‘sandwich.drush.inc’. You can find this file in the ‘examples’ directory in the drush distribution.

Drush searches for commandfiles in the following locations: • The “/path/to/drush/commands” folder.

• Folders listed in the ‘include’ option (see ‘drush topic docs-configuration‘). • The system-wide drush commands folder, e.g. /usr/share/drush/commands • The ”.drush” folder in the user’s HOME folder.

• /drush and /sites/all/drush in the current Drupal installation • All enabled modules in the current Drupal installation

(19)

• Folders and files containing other versions of drush in their names will be *skipped* (e.g. devel.drush4.inc or drush4/devel.drush.inc). Names containing the current version of drush (e.g. devel.drush5.inc) will be loaded. Note that modules in the current Drupal installation will only be considered if drush has bootstrapped to at least the DRUSH_BOOSTRAP_SITE level. Usually, when working with a Drupal site, drush will bootstrap to DRUSH_BOOTSTRAP_FULL; in this case, only the drush commandfiles in enabled modules will be considered eligible for loading. If drush only bootstraps to DRUSH_BOOTSTRAP_SITE, though, then all drush commandfiles will be considered, whether the module is enabled or not. See ‘drush topic docs-bootstrap‘ for more information on bootstrapping.

Additionally, drush commandfiles may optionally define a function COMMANDFILE_drush_load() in the file COM-MANDFILE.drush.load.inc. If this function returns FALSE, then the commandfile will not be loaded.

2.3.2 Implement COMMANDFILE_drush_command()

The drush_command hook is the most important part of the commandfile. It returns an array of items that define how your commands should be called, and how they work. Drush commands are very similar to the Drupal menu system. The elements that can appear in a drush command definition are shown below.

• ‘aliases’: Provides a list of shorter names for the command. For example, pm-download may also be called via ‘drush dl‘. If the alias is used, drush will substitute back in the primary command name, so pm-download will still be used to generate the command hook, etc.

• ‘command-hook’: Change the name of the function drush will call to execute the command from drush_COMMANDFILE_COMMANDNAME() to drush_COMMANDFILE_COMMANDHOOK(), where COMMANDNAME is the original name of the command, and COMMANDHOOK is the value of the ‘command-hook’ item.

• ‘callback’: Name of function to invoke for this command. The callback function name _must_ begin with “drush_commandfile_”, where commandfile is from the file “commandfile.drush.inc”, which contains the com-mandfile_drush_command() function that returned this command. Note that the callback entry is optional; it is preferable to omit it, in which case drush_invoke() will generate the hook function name.

• ‘callback arguments’: An array of arguments to pass to the callback. The command line arguments, if any, will appear after the callback arguments in the function parameters.

• ‘description’: Description of the command.

• ‘arguments’: An array of arguments that are understood by the command. Used by ‘drush help‘ only.

• ‘required-arguments’: Defaults to FALSE; TRUE if all of the arguments are required. Set to an integer count of required arguments if only some are required.

• ‘options’: An array of options that are understood by the command. Any option that the command expects to be able to query via drush_get_option _must_ be listed in the options array. If it is not, users will get an error about an “Unknown option” when they try to specify the option on the command line.

The value of each option may be either a simple string containing the option description, or an array containing the following information:

– ‘description’: A description of the option.

– ‘example-value’: An example value to show in help. – ‘value’: optional|required.

– ‘required’: This option must be passed.

– ‘hidden’: The option is not shown in the help output (rare).

(20)

• ‘allow-additional-options’: If TRUE, then the ordinary testing to see if options exist will be skipped. Examples of where this is done includes the core-rsync command, which passes options along to the rsync shell command. This item may also contain a list of other commands that are invoked as subcommands (e.g. the pm-update command calls pm-updatecode and updatedb commands). When this is done, the options from the subcommand may be used on the commandline, and are also listed in the command’s ‘help‘ output.

Defaults to FALSE.

• ‘examples’: An array of examples that are understood by the command. Used by ‘drush help‘ only. • ‘scope’: One of ‘system’, ‘project’, ‘site’. Not currently used.

• ‘bootstrap’: Drupal bootstrap level. Valid values are: – DRUSH_BOOTSTRAP_DRUSH – DRUSH_BOOTSTRAP_DRUPAL_ROOT – DRUSH_BOOTSTRAP_DRUPAL_SITE – DRUSH_BOOTSTRAP_DRUPAL_CONFIGURATION – DRUSH_BOOTSTRAP_DRUPAL_DATABASE – DRUSH_BOOTSTRAP_DRUPAL_FULL – DRUSH_BOOTSTRAP_DRUPAL_LOGIN – DRUSH_BOOTSTRAP_MAX

The default value is DRUSH_BOOTSTRAP_DRUPAL_LOGIN. See ‘drush topic docs-bootstrap‘. • ‘core’: Drupal major version required. Append a ‘+’ to indicate ‘and later versions.’

• ‘drupal dependencies’: Drupal modules required for this command.

• ‘drush dependencies’: Other drush commandfiles required for this command.

• ‘engines’: Provides a list of Drush engines to load with this command. The set of appropriate engines varies by command.

– ‘outputformat’: One important engine is the ‘outputformat’ engine. This engine is responsible for format-ting the structured data (usually an associative array) that a Drush command returns as its function result into a human-readable or machine-parsable string. Some of the options that may be used with output for-mat engines are listed below; however, each specific output forfor-mat type can take additional option items that control the way that the output is rendered. See the comment in the output format’s implementation for information. The Drush core output format engines can be found in commands/core/outputformat.

* ‘default’: The default type to render output as. If declared, the command should not print any output on its own, but instead should return a data structure (usually an associative array) that can be rendered by the output type selected.

* ‘pipe-format’: When the command is executed in –pipe mode, the command output will be rendered by the format specified by the pipe-format item instead of the default format. Note that in either event, the user may specify the format to use via the –format command-line option.

* ‘formatted-filter’ and ‘pipe-filter’: Specifies a function callback that will be used to filter the command result. The filter is selected based on the type of output format object selected. Most output formatters are ‘pipe’ formatters, that produce machine-parsable output. A few formatters, such as ‘table’ and ‘key-value’ are ‘formatted’ filter types, that produce human-readable output.

• ‘topics’: Provides a list of topic commands that are related in some way to this command. Used by ‘drush help‘. • ‘topic’: Set to TRUE if this command is a topic, callable from the ‘drush docs-topics‘ command.

(21)

• ‘category’: Set this to override the category in which your command is listed in help. The ‘sandwich’ drush_command hook looks like this:

function sandwich_drush_command() { $items = array();

$items[’make-me-a-sandwich’] = array(

’description’ => "Makes a delicious sandwich.", ’arguments’ => array(

’filling’ => ’The type of the sandwich (turkey, cheese, etc.)’, ),

’options’ => array(

’spreads’ => ’Comma delimited list of spreads (e.g. mayonnaise, mustard)’, ),

’examples’ => array(

’drush mmas turkey --spreads=ketchup,mustard’ => ’Make a terrible-tasting sandwich that is lacking in pickles.’, ),

’aliases’ => array(’mmas’),

’bootstrap’ => DRUSH_BOOTSTRAP_DRUSH, // No bootstrap at all. );

return $items; }

Most of the items in the ‘make-me-a-sandwich’ command definition have no effect on execution, and are used only by ‘drush help‘. The exceptions are ‘aliases’ (described above) and ‘bootstrap’. As previously mentioned, ‘drush topic docs-bootstrap‘ explains the drush bootstrapping process in detail.

2.3.3 Implement drush_COMMANDFILE_COMMANDNAME()

The ‘make-me-a-sandwich’ command in sandwich.drush.inc is defined as follows: function drush_sandwich_make_me_a_sandwich($filling = ’ascii’) {

... implementation here ... }

If a user runs ‘drush make-me-a-sandwich‘ with no command line arguments, then drush will call drush_sandwich_make_me_a_sandwich() with no function parameters; in this case, $filling will take on the provided default value, ‘ascii’. (If there is no default value provided, then the variable will be NULL, and a warning will be printed.) Running ‘drush make-me-a-sandwich ham‘ will cause drush to call drush_sandwich_make_me_a_sandwich(‘ham’). In the same way, commands that take two command line arguments can simply define two functional parameters, and a command that takes a variable number of command line arguments can use the standard php function func_get_args() to get them all in an array for easy processing.

It is also very easy to query the command options using the function drush_get_option(). For example, in the drush_sandwich_make_me_a_sandwich() function, the –spreads option is retrieved as follows:

$str_spreads = ’’;

if ($spreads = drush_get_option(’spreads’)) { $list = implode(’ and ’, explode(’,’, $spreads)); $str_spreads = ’ with just a dash of ’ . $list; }

Note that drush will actually call a sequence of functions before and after your drush command function. One of these hooks is the “validate” hook. The ‘sandwich’ commandfile provides a validate hook for the ‘make-me-a-sandwich’ command:

(22)

function drush_sandwich_make_me_a_sandwich_validate() { $name = posix_getpwuid(posix_geteuid());

if ($name[’name’] !== ’root’) {

return drush_set_error(’MAKE_IT_YOUSELF’, dt(’What? Make your own sandwich.’)); }

}

The validate function should call drush_set_error and return its result if the command cannot be validated for some reason. See ‘drush topic docs-policy‘ for more information on defining policy functions with validate hooks, and ‘drush topic docs-api‘ for information on how the command hook process works. Also, the list of defined drush error codes can be found in ‘drush topic docs-errorcodes‘.

To see the full implementation of the sample ‘make-me-a-sandwich’ command, see ‘drush topic docs-examplecommand‘.

2.4 Drush Contexts

The drush contexts API acts as a storage mechanism for all options, arguments and configuration settings that are loaded into drush.

This API also acts as an IPC mechanism between the different drush commands, and provides protection from acci-dentally overriding settings that are needed by other parts of the system.

It also avoids the necessity to pass references through the command chain and allows the scripts to keep track of whether any settings have changed since the previous execution.

This API defines several contexts that are used by default.

2.4.1 Argument contexts

These contexts are used by Drush to store information on the command. They have their own access functions in the forms of drush_set_arguments(), drush_get_arguments(), drush_set_command(), drush_get_command().

• command : The drush command being executed.

• arguments : Any additional arguments that were specified.

2.4.2 Setting contexts

These contexts store options that have been passed to the drush.php script, either through the use of any of the config files, directly from the command line through –option=’value’ or through a JSON encoded string passed through the STDIN pipe.

These contexts are accessible through the drush_get_option() and drush_set_option() functions. See drush_context_names() for a description of all of the contexts.

Drush commands may also choose to save settings for a specific context to the matching configuration file through the drush_save_config() function.

2.4.3 Available Setting contexts

These contexts are evaluated in a certain order, and the highest priority value is returned by default from drush_get_option. This allows scripts to check whether an option was different before the current execution.

(23)

• process : Generated in the current process. • cli : Passed as –option=value to the command line. • stdin : Passed as a JSON encoded string through stdin.

• alias : Defined in an alias record, and set in the alias context whenever that alias is used.

• specific : Defined in a command-specific option record, and set in the command context whenever that command is used.

Specified by config files :

• custom : Loaded from the config file specified by –config or -c • site : Loaded from the drushrc.php file in the Drupal site directory. • drupal : Loaded from the drushrc.php file in the Drupal root directory. • user : Loaded from the drushrc.php file in the user’s home directory. • drush : Loaded from the drushrc.php file in the $HOME/.drush directory.

• system : Loaded from the drushrc.php file in the system’s $PREFIX/etc/drush directory. • drush : Loaded from the drushrc.php file in the same directory as drush.php.

Specified by the script, but has the lowest priority :

• default : The script might provide some sensible defaults during init.

2.5 Running Drupal cron tasks from drush

Drupal cron tasks are often set up to be run via a wget call to cron.php; this same task can also be accomplished via the ‘drush cron‘ command, which circumvents the need to provide a webserver interface to cron.

2.5.1 Quickstart

If you just want to get started quickly, here is a crontab entry that will run cron once every hour at ten minutes after the hour:

10 * * * * /usr/bin/env PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin COLUMNS=72 /usr/local/drush/drush –root=/path/to/your/drupalroot –uri=your.drupalsite.org –quiet cron

You should set up crontab to run your cron tasks as the same user that runs the web server; for example, if you run your webserver as the user www-data:

sudo -u www-data crontab -e

You might need to edit the crontab entry shown above slightly for your paricular setup; for example, if you have in-stalled drush to some directory other than /usr/local/drush, then you will need to adjust the path to drush appropriately. We’ll break down the meaning of each section of the crontab entry in the documentation that continues below.

2.5.2 Setting the schedule

See‘man 5 crontab‘for information on how to format the information in a crontab entry. In the example above, the schedule for the crontab is set by the string “10 * * * *”. These fields are the minute, hour, day of month, month and day of week; “*” means essentially “all values”, so “10 * * * *” will run any time the minute == 10 (once every hour).

(24)

2.5.3 Setting the PATH

We use /usr/bin/env to run drush so that we can set up some necessary environment variables that drush needs to execute. By default, cron will run each command with an empty PATH, which would not work well with drush. To find out what your PATH needs to be, just type:

echo $PATH

Take the value that is output and place it into your crontab entry in the place of the one shown above. You can remove any entry that is known to not be of interest to drush (e.g. /usr/games), or is only useful in a graphic environment (e.g. /usr/X11/bin).

2.5.4 Setting COLUMNS

When running drush in a terminal, the number of columns will be automatically deteremined by drush by way of the tput command, which queries the active terminal to determine what the width of the screen is. When running drush from cron, there will not be any terminal set, and the call to tput will produce an error message. Spurrious error messages are undesirable, as cron is often configured to send email whenever any output is produced, so it is important to make an effort to insure that successful runs of cron complete with no output.

In some cases, drush is smart enough to recognize that there is no terminal – if the terminal value is empty or “dumb”, for example. However, there are some “non-terminal” values that drush does not recognize, such as “unknown.” If you manually set COLUMNS, then drush will repect your setting and will not attempt to call tput.

2.5.5 Using –quiet

By default, drush will print a success message when the run of cron is completed. The –quiet flag will suppress these and other progress messages, again avoiding an unnecessary email message.

2.5.6 Specifying the Drupal site to run

There are many ways to tell drush which Drupal site to select for the active command, and any may be used here. The example uses the –root and –uri flags, but you could also use an alias record if you defined it in a global location, such as /etc/drush/aliases.drushrc.php.

2.6 Drush Shell Aliases

A Drush shell alias is a shortcut to any Drush command or any shell command. Drush shell aliases are very similar to git aliases.

See:https://git.wiki.kernel.org/index.php/Aliases#Advanced

A shell alias is defined in a Drush configuration file called drushrc.php. See ‘drush topic docs-configuration‘. There are two kinds of shell aliases: an alias whose value begins with a ‘!’ will execute the rest of the line as bash commands. Aliases that do not start with a ‘!’ will be interpreted as Drush commands.

2.6.1 Example:

$options[’shell-aliases’][’pull’] = ’!git pull’;

(25)

With the above two aliases defined, ‘drush pull‘ will then be equivalent to ‘git pull‘, and ‘drush noncore‘ will be equivalent to ‘drush pm-list –no-core‘.

Shell Alias Replacements

Shell aliases are even more powerful when combined with shell alias replacements and site aliases. Shell alias re-placements take the form of {{sitealias-item}} or {{%pathalias-item}}, and also the special{{@target}}, which is replaced with the name of the site alias used, or‘@none‘ if none was used.

For example, given the following site alias: $aliases[’dev’] = array (

’root’ => ’/path/to/drupal’, ’uri’ => ’mysite.org’, ’#live’ => ’@acme.live’, );

The alias below can be used for all your projects to fetch the database and files from the client’s live site via ‘drush @dev pull-data‘. Note that these aliases assume that the alias used defines an item named ‘#live’ (as shown in the above alias).

2.6.2 Shell aliases using replacements:

$options[’shell-aliases’][’pull-data’] = ’!drush sql-sync {{#live}} {{@target}} && drush rsync {{#live}}:%files {{@target}}:%files’;

If the user does not use these shell aliases with any site alias, then an error will be returned and the script will not run. These aliases with replacements can be used to quickly run combinations of drush sql-sync and rsync commands on the “standard” source or target site, reducing the risk of typos that might send information in the wrong direction or to the wrong site.

2.7 Drush Shell Scripts

A drush shell script is any Unix shell script file that has its “execute” bit set (i.e., via ‘chmod +x myscript.drush‘) and that begins with a specific line:

#!/usr/bin/env drush • or

-#!/full/path/to/drush

The former is the usual form, and is more convenient in that it will allow you to run the script regardless of where drush has been installed on your system, as long as it appears in your PATH. The later form allows you to specify the drush command add options to use, as in:

#!/full/path/to/drush php-script --some-option

Adding specific options is important only in certain cases, described later; it is usually not necessary.

Drush scripts do not need to be named “*.drush” or “*.script”; they can be named anything at all. To run them, make sure they are executable (‘chmod +x helloworld.script‘) and then run them from the shell like any other script. There are two big advantages to drush scripts over bash scripts:

• They are written in php

(26)

• drush can bootstrap your Drupal site before running your script.

To bootstrap a Drupal site, provide an alias to the site to bootstrap as the first commandline argument. For example:

$ helloworld.script @dev a b c

If the first argument is a valid site alias, drush will remove it from the arument list and bootstrap that site, then run your script. The script itself will not see @dev on its argument list. If you do not want drush to remove the first site alias from your scripts argument list (e.g. if your script wishes to syncronise two sites, specified by the first two arguments, and does not want to bootstrap either of those two sites), then fully specify the drush command (php-script) and options to use, as shown above. By default, if the drush command is not specified, drush will provide the following default line:

#!/full/path/to/drush php-script --bootstrap-to-first-arg

It is the option –bootstrap-to-first-arg that causes drush to pull off the first argument and bootstrap it. The way to get rid of that option is to specify the php-script line to run, and leave it off, like so:

#!/full/path/to/drush php-script

Note that ‘php-script’ is the only built-in drush command that makes sense to put on the “shebang” (“#!” is pronounced “shebang”) line. However, if you wanted to, you could implement your own custom version of php-script (e.g. to preprocess the script input, perhaps), and specify that command on the shebang line.

Drush scripts can access their arguments via the drush_shift() function: while ($arg = drush_shift()) {

drush_print($arg); }

Options are available via drush_get_option(‘option-name’).

See the example drush script in ‘drush topic docs-examplescript‘, and the list of drush error codes in ‘drush topic docs-errorcodes‘.

2.8 Strict Option Handling

Some Drush commands use strict option handling; these commands require that all Drush global option appear on the command line before the Drush command name.

One example of this is the core-rsync command:

drush --simulate core-rsync -v @site1 @site2

The –simulate option is a Drush global option that causes Drush to print out what it would do if the command is executed, without actually taking any action. Commands such as core-rsync that use strict option handling require that –simulate, if used, must appear before the command name. Most Drush commands allow the –simulate to be placed anywhere, such as at the end of the command line.

The -v option above is an rsync option. In this usage, it will cause the rsync command to run in verbose mode. It will not cause Drush to run in verbose mode, though, because it appears after the core-rsync command name. Most Drush commands would be run in verbose mode if a -v option appeared in the same location.

The advantage of strict option handling is that it allows Drush to pass options and arguments through to a shell command. Some shell commands, such as rsync and ssh, either have options that cannot be represented in Drush. For example, rsync allows the –exclude option to appear multiple times on the command line, but Drush only allows one instance of an option at a time for most Drush commands. Strict option handling overcomes this limitation,

(27)

plus possible conflict between Drush options and shell command options with the same name, at the cost of greater restriction on where global options can be placed.

(28)
(29)

Indices and tables

• genindex

• search

master PHPUnit. http://www.drush.org. Drupal Answers. GitHub Drush Issue Queue. fixed bugs, unmigrated issues, unmigratedbugs https://github.com/drush-ops/drush/releases.atom A list of modules that include Drush integration Resources Drush FAQ. Install Composer globally Fuller explanation of the require command. http://drupal.org/node/207036. http://www.drush.org/drush_windows_installer. http://drupal.org/node/594744. http://msysgit.github.com/. http://default. http://drupal.org/node/670460 Arto Bendiken Franz Heinzmann Moshe Weitzman bastion server https://git.wiki.kernel.org/index.php/Aliases#Advanced

References

Related documents

[r]

•The Maze Runner •The Missing Series •The Power of Six •Slated Series. •The Time Machine •A Wrinkle in Time Award

KCAS male subjects had significantly better results (Tables 2 and 3) than THCC male subjects in ACSM’s push up test, both dominant and non- dominant handgrip strength test, stork

Writing Skills, Reading Skills, Mathematical Reasoning Skills, and Thinking Skills(General Ability) Comprehension, Grammar, Vocabulary, Exam Techniques &amp; Lateral Thinking..

Eight years ago, at the start of 2013, I gave a sermon entitled, “My First and Only Star Trek Geek Sermon,” asking those who heard it to indulge my obsession “just this

But despite these actions, Christians all too often, leave the church and go into the world and say things that are not consistent with being a Christian or act in ways that are

given the ambiguous language of paragraph 32 of the Plan, the magistrate erred in finding her in contempt for moving out of the Forest Hills School District; (2) the magistrate

If the voltmeter reads voltage, the temperature control and the manual reset hi-limit switch are not keeping the heater from firing.. Make sure the pilot burner is positioned next