Writing directly executable drush scripts

Writing directly executable drush scripts

Submitted by Jitesh Doshi on Thu, 08/15/2013 - 11:41
Drupal Shell - Drush

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.

Jitesh Doshi

Profile picture for user Jitesh Doshi
Managing Partner & CTO
  • A seasoned technology entrepreneur and enthusiast
  • A regular speaker at industry conferences and universities
  • Host and organizer of technology user groups
  • Active in management of non-profit organizations serving the local community
  • Leader and contributor for multiple open-source projects
  • Expert in cloud, application integration, web and mobile technologies
  • Author of open-source projects, including on Drupal.org - Popular Tags and PRLP.
  • Developed several highly successful software platforms and frameworks for clients