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

utdev
  • 3,942
  • 8
  • 40
  • 70

4 Answers4

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
}
John
  • 1
  • 13
  • 98
  • 177
Mister M
  • 1,539
  • 3
  • 17
  • 37
3

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

BVengerov
  • 2,947
  • 1
  • 18
  • 32
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

Marius Bogdan
  • 424
  • 4
  • 10
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.

Edmund Dantes
  • 171
  • 4
  • 10