2016-09-30 109 views
2

我基本上想檢查一個命令是否使用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

回答

0

你可以這樣做:

$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

0

這將取決於你的命令是否返回任何輸出。據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函數的返回值。

1

如果您只需要命令的退出代碼,則應該使用exec而不是shell_exec

2

使用exec

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

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

我沒有定義$輸出也不$返回正確的嘗試? – utdev

+0

不只是使用上面的代碼 –

+0

我得到這個錯誤undefined變量$輸出 – utdev