Home > Mobile >  Symfony: Redirect output of a Process
Symfony: Redirect output of a Process

Time:12-02

I am upgrading an old Symfony application (v2.8) to Symfony 5.3. I am using the process component where the arguments have to be passed in another way than before.

My previous code was like

use Symfony\Component\Process\Process;

$cmd = sprintf('mysqldump mydatabase > %s', $outputTarget);
$process = new Process($cmd);
$process->run();

Now, Symfony's Process constructor expects the binary and the arguments to be passed as array (see here).

How can I achieve the output redirection with the new style?

$process = new Process(['mysqldump', 'mydatabase', '>', $outputTarget]);
$process->run();

Won't work, because the > would be escaped.

CodePudding user response:

I have found a workaround. Process::fromShellCommandline can be used to redirect the output. This is my solution:

$process = Process::fromShellCommandline('mysqldump mydatabase > "$OUTPUT_TARGET"');
$process->start(null, [
    'OUTPUT_TARGET' => $outputTarget,
]);

This way the arguments get passed as environment variables to the process and the OS (or the shell?) takes care about replacing the placeholders of the command by the env.

  • Related