3

I would like to write an interactive Drush script that potentially makes a change to all pages of a website. Let's say we would would like to change "Foo" to "Baz" on each page. We want to review each changed page before it is saved. The code would look something like this:

foreach(website as node) {
  if node->body->value contains "Foo" {
    change "Foo" to "Baz" and display the changed version of body for the user
    Prompt User: Commit change? Yes or No
    if "Yes", save the node
    }
}

It appears Drush is buffering output so that I can not interact with the user in this way. Is this possible?

3 Answers 3

5

Drush has built-in functions to handle I/O.

If you're using Drush <9.x, there's the procedural drush_confirm() that will prompt a user for a response to a given message. If you're using 9.x+, any custom command class extending the DrushCommands class will have access to the $this->io()->confirm method which does the same thing with Symphony's CLI components.

See the latest Drush docs for more info on I/O.

1
  • Thank you @Shawn Conn!! Greg
    – Greg Sims
    Commented Apr 22, 2020 at 20:47
2

I found the following 3 ways to prompt for user input in Drush which contains a solution.

if (drush_confirm('Print \'Hello world\' to the screen?')) {
  drush_print('Hello world!');
}
else {
  drush_user_abort();
}
0

On New drush versions, can you use the below, in a both command file and as drush script e.g. drush scr /path/to/script.php

use Drush\Exceptions\UserAbortException;

// Script to setup the round theme.
$do_run_if_no_input = FALSE;
$answer = $this->io()->confirm('Do you want to continue?', $do_run_if_no_input);
if (!$answer) {
    throw new UserAbortException("Command cancelled.");
}
$this->io()->writeln('Continuing...');

@see https://github.com/drush-ops/example-drush-extension/blob/master/ExampleCommands.php

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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