Search code examples
phpshell-exec

How to execute multi line command with shell_exec?


I am trying to run a multi line shell in shell_exec

$cmd = <<<CMD
convert  /home//test.jpg 
-font Nimbus-Sans-L -pointsize 20  \
-draw "gravity south  fill black  text 0,12 'Copyright'  fill white  text 1,11 'Copyright' " \ 
test2.jpg
CMD;

I tried with \ with \\ and even with \\\ and also without any !

What is the correct syntax ?


Solution

  • You're missing a trailing \ backslash on the first line of the command. It should be:

    $cmd = <<<CMD
    convert  /home//test.jpg \
    -font Nimbus-Sans-L -pointsize 20  \
    -draw "gravity south  fill black  text 0,12 'Copyright'  fill white  text 1,11 'Copyright' " \ 
    test2.jpg
    CMD;
    

    See that this works as expected:

    <?php
    
    $cmd = <<<CMD
    echo abc \
    def \
    ghi
    CMD;
    
    print_r(shell_exec($cmd));
    
    $ php test.php
    abc def ghi