Writing directly executable drush scripts
Submitted by Jitesh Doshi
on Thu, 08/15/2013 - 11:41
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 ...
- There is no "<?php" tag.
- The first line follows UNIX convention for scripts by string with "#!" followed by the path of the interpreter that should run this script.
- 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.