August 5, 2008

Drupal shell: quickly evaluating PHP statements in a Drupal context

August 5, 2008 - Categories: drupal

I often find myself needing to variable_set something temporarily, just to try things out. The drush module provides a command-line interface that solves this problem with a little more hacking. To minimize the effect on my source tree, I’ve unpacked it into the sites directory for my local installation and enabled it in my test database. After I enabled the main drush module and the related modules, I tweaked drush_tools to include an insecure-but-useful eval command. Here it is:

--- sites/local.example.com/modules/drush/drush_tools.module.orig    2008-08-05 17:18:48.000000000 -0400
+++ sites/local.example.com/modules/drush/drush_tools.module    2008-08-05 17:18:55.000000000 -0400
@@ -46,6 +46,10 @@
     'callback' => 'drush_tools_sync',
     'description' => 'Rsync the Drupal tree to/from another server using ssh'
   );
+  $items['eval'] = array(
+    'callback' => 'drush_tools_eval',
+    'description' => 'Evaluate a command',
+  );
   return $items;
 }
 
@@ -156,3 +160,6 @@
   }
 }
 
+function drush_tools_eval($command) {
+  eval($command);
+}

I also added an alias to my ~/.bashrc along the lines of:

alias drush='php ~/drupal/sites/local.example.com/modules/drush/drush.php -r ~/drupal -l http://local.example.com'

where ~/drupal is my multisite Drupal directory root.

After I loaded the alias with “source ~/.bashrc”, I can now execute PHP statements in my Drupal context with commands like:

drush eval "variable_set('hello', 'world');"

Good stuff!