gpt4 book ai didi

php - sh: 2: 1: not found - 将多个 php 参数传递给 bash 脚本

转载 作者:太空狗 更新时间:2023-10-29 12:01:18 24 4
gpt4 key购买 nike

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

$webroot = getcwd();

function get_version($name)
{
global $webroot;

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

return $version;
}

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

#!/bin/bash

_x=""
_programm=$1
_nr=$2

if [ "$_nr" -eq "1" ] ; then
_x=$($_programm -v 2>/dev/null | grep -i 'version' | awk -F/ '{ print $4 }')
elif [ "$_nr" -eq "2" ] ; then
_x=$($_programm -v 2>&1 | awk -F/ '{ print $2 }')
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 switch 语句中的命令 whereis 出于某种未知原因向路径变量写入了一个空格字符,因此它无法正常工作。我在我的 $path 变量上使用了 rtrim 来修复它。

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

关于php - sh: 2: 1: not found - 将多个 php 参数传递给 bash 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35127238/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com