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:
- There is no ”<?php” tag.
- The first line follows UNIX convention for scripts by starting with ”#!” followed by the path of the interpreter.
- The command-line args are extracted with “drush_shift()” and iterated over in a loop.
- Printing is done with drush_print()
I hope this helps others write cleaner drush scripts and do better Drupal automation.