Black
Black

Reputation: 20232

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

I have a simple bash script which i call from my php code to find out the version of my apache and 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;
}

As you can see i call my bash script with two arguments passed. The path and a integer number which i use in my bash script:

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

Output of function:

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

But if i execute the bash script in the terminal, then it works and i get the version number as output, i tried it both with user root and www-data, both worked. The bash script is also entered in the visudo file and has execute rights, the user of the script is www-data.

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

Can someone please explain why it does work in terminal but not in php?

Upvotes: 2

Views: 1451

Answers (2)

Black
Black

Reputation: 20232

i found the problem and the solution. The command whereis in my php switch statement wrote a space character to the path variable for some unknown reason, so it did not worked because of it. I used rtrim on my $path variable to fix it.

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

Upvotes: 2

maxhb
maxhb

Reputation: 8855

You have to escape $ if you are using it inside double quotes in php or switch to single quotes:

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

Upvotes: 1

Related Questions