I'm writing a drush command, and outputting the results in table format. Everything works fine, the command runs, the output is displayed where it should be. However, there is one column where I am putting "Ok", "Warning", "Error" and I would like to be able to add color to that (the way drush does for its own commands). Yet I have looked everywhere without success to find instructions about how to do it, and would welcome some pointers.


In Drush 8 you may access Symfony Console output object directly.


 * @file
 * Contains example drush command.

use Symfony\Component\Console\Output\ConsoleOutput;

 * Implements hook_drush_command().
function MODULENAME_drush_command() {
  $items['example'] = [
    'description' => 'Command description.',
  return $items;

 * Callback function for example command.
 * @see http://symfony.com/doc/current/console/coloring.html#using-color-styles
function drush_MODULENAME_example() {
  $output = new ConsoleOutput();
  $output->writeln('<info>Green text</info>');
  $output->writeln('<comment>Yellow text</comment>');
  $output->writeln('<question>Black text on a cyan background</question>');
  $output->writeln('<error>White text on a red background</error>');

We should discuss this in the Drush issue queue. In Drush 8 and earlier, the code to support colored output exists in the logger only, and is not readily usable for other purposes.

In Drush 9, however, we are using the Symfony Console Output classes, so it should be possible to allow you to use the techniques in the Symfony Style Guide, or just wrap you text in <info> et. al.

Some minor enhancement may be necessary.


I added an example to Drush 9 that demonstrates how to use a cell data render function to add color to table output when --format=table is used without having the same transformation applied when the format is json, yaml or similar outputs. Note that the same technique can be used in instances where you wish to reduce an array to a string (e.g. via implode) when it is output in a table, and leave it as an array in yaml/json formats.

If you just want to insert color into older versions of Drush, and you don't mind it also appearing in yaml / json output, you can just use the terminal shell escapes directly:

$red = "\033[31;40m\033[1m[%s]\033[0m";
$yellow = "\033[1;33;40m\033[1m[%s]\033[0m";
$green = "\033[1;32;40m\033[1m[%s]\033[0m";

This isn't a great solution, though. You could use the Symfony table helper directly, as the other answer suggested, but then you wouldn't be able to convert your command output to other formats at all.

Perhaps we could backport the Console output handling to Drush 8; however, I'm not sure how much of a priority that will be.

  • I think I'll wait for Drush 9! – Joel Guesclin Nov 19 '16 at 16:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.