如何使用PHP检查命令是否存在

事实证明,我们可以使用 command -v [command name] 实用程序来检查系统上是否存在其他命令,这是在 Linux 和 bash 脚本中执行此操作的“标准”方法。

command实用程序可用于执行命令,也可用于返回现有命令的路径。

将可执行文件与 -v 参数一起使用时将返回可执行文件的路径,如果实用程序未产生任何输出,则返回 NULL。

知道了这一点,我们现在可以创建我们自己的 command_exists() 函数:

/**
 * 检查命令是否存在于典型的 Linux 系统上
 * @param mixed $command_name 
 * @return bool 
 */
public function command_exists($command_name)
{
   return (null === shell_exec("command -v $command_name")) ? false : true;
}

这个函数可以用作 PHP 中的任何其他 *_exists 函数:

if (false === command_exists('convert')) {
   throw new Exception("The required command 'convert' does not appear to exist on the system.");
}
$command = "convert this.jpeg that.avif";
$result = shell_exec(escapeshellcmd($command));

跨平台兼容性

为了使其在 Linux 和 Windows 上都能工作,我们应该检查 PHP_OS 常量变量。
该常量包含运行 PHP 的操作系统,我们可以使用它来确定判断命令是否可用的方法。

Windows 系统使用 where 实用程序,而 Linux 通常使用command -v 实用程序。

以下是确定使用哪种方法的代码:

if (false === stripos(PHP_OS, 'linux')) {
   $test_method = 'command -v';
} else if (false === stripos(PHP_OS, 'win')) {
   throw new Exception('This OS is not supported.');
} else {
   $test_method = 'where';
}
if (null === shell_exec("$test_method $command_name")) {
  echo 'Command not found!';
  exit();
} else {
  echo 'Command was found.';
  exit();
}

这可以缩短为:

/**
 * Checks if a command exist. Works for both Windows and Linux systems
 * @param mixed $command_name 
 * @return bool 
 */
public function command_exists($command_name)
{
   $test_method = (false === stripos(PHP_OS, 'win')) ? 'command -v' : 'where';
   return (null === shell_exec("$test_method $command_name")) ? false : true;
}

但是,在这种情况下,跨平台兼容性测试几乎完全无关紧要,因为无论如何我们都不会像在典型的 Linux 发行版中那样拥有可用于 Windows 的相同命令。

PHP检查一个命令是否可执行

当然,知道命令是否也可执行可能很重要,但不幸的是,仅靠 PHP 是不可能的。
我的猜测是,知道一个命令是否也是可执行的对于大多数用途来说都是无关紧要的,但如果需要,我们可以只使用帮助程序 .sh 帮助程序脚本。

PHP is_executable 仅在某些情况下有效;实际上,即使对于可执行的命令,它也可能返回 false。

参考代码如下:

#!/bin/bash
##  Helper script to check for dependencies
##  This script can be placed in /usr/local/bin/
## script author: jack
#  |>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>|
#  |>>>>>>>Execute>>>>>>>>>>>>>>>>>>>>>>>>|
#  |>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>|
if [ "" = "" ]
then
 printf "\n Error: Missing required command line parameter: [command name]\n\n"
 exit 1
fi 
if [ ! -x "$(command -v )" ]
then
  printf "\n This script requires \"\" to be installed. Exiting.\n\n"
  # Exit with 2 = Missing keyword or command, or permission problem...
  # See also: http://www.comp.org/LDP/abs/html/exitcodes.html
  # A zero code indicates success, while a value higher than zero indicates an error
  exit 2
fi
日期:2020-06-02 22:17:06 来源:oir作者:oir