8

I basically want to check if a command ran successfully using shell_exec.

Simple function:

public static function foo()
{
    $command = "blabla";
    shell_exec($command);
}

Edit, I tried Mister M's suggestion like this:

foreach($commands as $key => $value)
{
    shell_exec($value, $output, $return);
}

And I get this error:

Undefined variable: output

4 Answers 4

10

Try using exec:

$output = array();//Each line will be assigned to this array if any are generated.
$result1 = exec($command, $output, $return);

if ($return != 0)
{
 // error occurred
}
else
{
 // success
}
2
  • I do not have to define $output nor $return correct ?
    – utdev
    Sep 30, 2016 at 14:09
  • are you redirecting stderr? I mean add this to the end of your $command: "2>&1" so it's like "your command 2>&1"
    – Mister M
    Oct 4, 2016 at 11:54
3

You should use exec instead of shell_exec if you need only the exit code of the command.

0

You can do this:

$output = shell_exec('ls -lart');
echo "<pre>$output</pre>";

and validate the output.

But according to the manual:

Note: This function can return NULL both when an error occurs or the program produces no output. It is not possible to detect execution failures using this function. exec() should be used when access to the program exit code is required.

http://php.net/shell_exec

0

It would depend whether your command returns any output. According to PHP docs:

shell_exec — Execute command via shell and return the complete output as a string

and:

Return Values

The output from the executed command or NULL if an error occurred or the command produces no output.

Note: This function can return NULL both when an error occurs or the program produces no output. It is not possible to detect execution failures using this function. exec() should be used when access to the program exit code is required.

So, if you can expect the output in your command to appear, just catch the return value of shell_exec function.

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.