sh: 2: 1: 未找到 - 将多个 php 参数传递给 bash 脚本

sh: 2: 1: not found - pass multiple php arguments to bash script

我有一个简单的 bash 脚本,我从我的 php 代码调用它来找出我的 apache 和 nginx 的版本。

$webroot = getcwd();

function get_version($name)
{
    global $webroot;

    switch ($name)
    {
        case "apache":
            $path   = shell_exec("whereis apachectl | awk '{ print  }'");
            $version = shell_exec("sudo $webroot/scripts/get_version $path 1 2>&1");
            break;
        case "nginx":
            $path = shell_exec("whereis nginx | awk '{ print  }'");
            $version = shell_exec("sudo $webroot/scripts/get_version $path 2 2>&1");
        default:
            echo "error";
    }

    return $version;
}

如您所见,我调用 bash 脚本时传递了两个参数。我在 bash 脚本中使用的路径和整数:

#!/bin/bash

_x=""
_programm=
_nr=

if [ "$_nr" -eq "1" ] ; then
    _x=$($_programm -v 2>/dev/null | grep -i 'version' | awk -F/ '{ print  }')
elif [ "$_nr" -eq "2" ] ; then
    _x=$($_programm -v 2>&1 | awk -F/ '{ print  }')
fi

cd $(pwd)
echo $_x

函数输出:

get_version("apache");     OUTPUT:     sh: 2: 1: not found
get_version("nginx");      OUTPUT:     sh: 2: 2: not found

但是如果我在终端中执行 bash 脚本,那么它就可以工作并且我得到版本号作为输出,我在用户 rootwww-data 上都试过了,两者都有效。 bash脚本也进入了visudo文件,具有执行权限,脚本的用户为www-data.

./get_version /usr/sbin/apachectl 1     OUTPUT: 2.2.2
./get_version /usr/sbin/nginx 2         OUTPUT: 1.3

有人可以解释为什么它在终端中有效但在 php 中无效吗?

如果在 php 中的双引号内使用它,则必须转义 $ 或切换到单引号:

...
$path   = shell_exec('whereis apachectl | awk \'{ print  }\'');
...
$path = shell_exec('whereis nginx | awk \'{ print  }\'');

我找到了问题和解决方案。我的 php switch 语句中的命令 whereis 出于某种未知原因向路径变量写入了一个 space 字符,因此它无法正常工作。我在 $path 变量上使用 rtrim 来修复它。

    case "apache":
        $path   = shell_exec("whereis apachectl | awk '{ print  }'");
        $path   = rtrim($path);
        ...