Php检查shell_exec命令是否成功

问题描述:

我基本上想检查一个命令是否使用shell_exec运行成功。Php检查shell_exec命令是否成功

简单的函数:

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

编辑,我想先生M的建议是这样的:

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

而且我得到这个错误:

Undefined variable: output

你可以这样做:

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

并验证输出。

但根据手册:

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

这将取决于你的命令是否返回任何输出。据PHP docs

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

和:

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.

所以,如果你可以期望在你的命令的输出出现,正好赶上了shell_exec函数的返回值。

如果您只需要命令的退出代码,则应该使用exec而不是shell_exec

使用exec

exec($command, $output, $return); 

if ($return != 0) { 
    // error occurred 
}else{ 
    // success 
} 
+0

我没有定义$输出也不$返回正确的尝试? – utdev

+0

不只是使用上面的代码 –

+0

我得到这个错误undefined变量$输出 – utdev