php run cli command

最後更新: 2024-10-17

目錄

 


shell_exec

 

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

shell_exec(string $command): string|false|null
  • false if the pipe cannot be established
  • null if an error occurs or the command produces no output.

注意

它會保留了 output 的 newline. 所以要保存再用的 Variable 用 exec() 更好.

<?
  $a = shell_exec("echo 'a'");
  $o = shell_exec("echo $a | echo");
  echo $o
?>

error

sh: -c: line 1: syntax error near unexpected token `|'
sh: -c: line 1: ` | echo'

Usage

https://datahunter.org/ha_status_scripts#php

 


passthru

 

Execute an external program and display raw output

passthru(string $command, int &$result_code = null): ?false

Parameters

result_code

If the result_code argument is present, the return status of the Unix command will be placed here.

Returns

null on success or false on failure.

output buffer

ob_start();
passthru('echo $PATH');
$var = ob_get_contents();
ob_end_clean(); //Use this instead of ob_flush()

 


exec

 

亮點係 output to arrary

 exec(string $command, array &$output = null, int &$result_code = null): string|false

Return Values

The last line from the result of the command.

 


Set $PATH in PHP

 

set it only in specific circumstances

e.g.

exec("PATH=/sbin ip addr show");

 

 

Creative Commons license icon Creative Commons license icon