SpinSpire logo

Writing directly executable drush scripts

Often we write "drush" scripts to do Drupal task automation. For example, if you want to do delete domain_conf variables on your website, you might write a script like this ...

<?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. Overall, it doesn't feel right in the spirit of UNIX scripts.

So here's a better way. Rewrite the above script as follows ...

#!/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 string with "#!" followed by the path of the interpreter that should run this script.
  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.


tags: Knowledge Base drupal drush