Writing Directly Executable Drush Scripts

2013-08-15

Jitesh Doshi

Writing Directly Executable Drush Scripts

How to write self-executing drush scripts with shebang line and command-line argument handling.

Often we write “drush” scripts to do Drupal task automation. For example:

<?php
$variable_name = 'foo';
$domains = domain_domains();
foreach($domains as $domain_id => $domain) {
  print("Deleting $variable_name from ${domain['machine_name']} ($domain_id)");
  domain_conf_variable_delete($domain_id, $variable_name);
}

Save the above in myscript.php, and then execute it as “drush php-script myscript.php”.

That works okay, but it is not optimal. The invocation is a bit cumbersome, and you can’t pass the name of the variable as command line arg.

Here’s a better way:

#!/usr/bin/drush
while ($variable_name = drush_shift()) {
  $domains = domain_domains();
  foreach($domains as $domain_id => $domain) {
    drush_print("Deleting $variable_name from ${domain['machine_name']} ($domain_id)");
    domain_conf_variable_delete($domain_id, $variable_name);
  }
}

Notice the following:

  1. There is no ”<?php” tag.
  2. The first line follows UNIX convention for scripts by starting with ”#!” followed by the path of the interpreter.
  3. The command-line args are extracted with “drush_shift()” and iterated over in a loop.
  4. Printing is done with drush_print()

I hope this helps others write cleaner drush scripts and do better Drupal automation.