Drupal - How to execute php script using drush?
You can convert the script in a Drush shell script.
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
Drush scripts are better than Bash scripts for the following reasons:
- They are written in PHP
- Drush can bootstrap the site before running the script
The following is the example you can find on helloword.script.
#!/usr/bin/env drush
//
// This example demonstrates how to write a drush
// "shebang" script. These scripts start with the
// line "#!/usr/bin/env drush" or "#!/full/path/to/drush".
//
// See `drush topic docs-scripts` for more information.
//
drush_print("Hello world!");
drush_print();
drush_print("The arguments to this command were:");
//
// If called with --everything, use drush_get_arguments
// to print the commandline arguments. Note that this
// call will include 'php-script' (the drush command)
// and the path to this script.
//
if (drush_get_option('everything')) {
drush_print(" " . implode("\n ", drush_get_arguments()));
}
//
// If --everything is not included, then use
// drush_shift to pull off the arguments one at
// a time. drush_shift only returns the user
// commandline arguments, and does not include
// the drush command or the path to this script.
//
else {
while ($arg = drush_shift()) {
drush_print(' ' . $arg);
}
}
drush_print();
You can made the script executable, so you can execute it with <script file> <parameters>
where <script name>
is the script name, and <parameters>
are the parameters passed to the script; if the script is not executable, you call it with drush <script name> <parameters>
.
With drush php-eval
, you can run your script without having to save it to a file first:
drush php-eval '
$uid = 1234;
$query = db_query("SELECT cid FROM {comments} WHERE uid = %d", $uid);
while($cid = db_result($query)) {
comment_delete($cid);
}
'
This uses nested quotation marks, so to prevent a mess I recommend to use only double quotes "
within the PHP code.
I think you're looking at drush -d scr --uri=example.org sample_script.php
to execute sample_script.php.