sh:2:1:未find – 将多个phpparameter passing给bash脚本

我有一个简单的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脚本中使用的path和整数:

 #!/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 

function输出:

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

但是,如果我在terminal执行bash脚本,那么它的工作原理,我得到的版本号作为输出,我试图用用户rootwww-data ,都工作。 bash脚本也被input到visudo文件中并具有执行权限,脚本的用户是www-data。

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

有人可以请解释为什么它在terminal工作,而不是在PHP?

我发现问题和解决方案。 在我的PHP开关语句的whereis命令写了一个空格字符的路径变量为某些未知的原因,所以它没有工作,因为它。 我在我的$path变量上使用rtrim来修复它。

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

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

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