How to pass a command line to Symfony Process component

1k views Asked by At

I've tried to pass the following command line to Symfony Process component according to Symfony documentation:

use Symfony\Component\Process\Exception\ProcessFailedException;
use Symfony\Component\Process\Process;

$process = new Process(['cat crons/* | crontab -']);
$process->run();

and also the following:

$process = new Process(['cat crons/*', '|', 'crontab -']);

and:

['cat crons/*', '|', 'crontab', '-']

but it doesn't work, it rises an exception:

 The command "'cat /var/www/config/crontab/* | crontab -'" failed.       
                                                                          
  Exit Code: 127(Command not found)                                       
                                                                          
  Working directory: /var/www                                             
                                                                          
  Output:                                                                 
  ================                                                        
                                                                          
                                                                          
  Error Output:                                                           
  ================                                                        
  sh: exec: line 1: cat /var/www/config/crontab/* | crontab -: not found

Have anyone a solution please ?

1

There are 1 answers

0
miken32 On

The documentation says:

Using an array of arguments is the recommended way to define commands. This saves you from any escaping and allows sending signals seamlessly (e.g. to stop processes while they run):

$process = new Process(['/path/command', '--option', 'argument', 'etc.']);
$process = new Process(['/path/to/php', '--define', 'memory_limit=1024M', '/path/to/script.php']);

If you need to use stream redirections, conditional execution, or any other feature provided by the shell of your operating system, you can also define commands as strings using the fromShellCommandline() static factory.

So if you are providing your command as an array, you do not put the entire command into a single array argument. And, if you are trying to do things like redirects, you do not use an array at all.

use Symfony\Component\Process\Exception\ProcessFailedException;
use Symfony\Component\Process\Process;

$process = Process::fromShellCommandLine('cat crons/* | crontab -');
try {
    $process->run();
} catch (ProcessFailedException $e) {
    ...
}