0

I have a bash script where I want to pass a variable into a PHP script, the PHP script will execute and return something which should be stored in a bash variable. My bash script code is like so

ip="192.168.1.4"
version=`/usr/bin/php checkVer.php $ip`

So in these two lines of code, I want to pass $ip as a variable to the checkVer.php script and then the script will execute some code, return something, and that return will be stored in the bash variable version. However, version= is only returning the $ip variable. Why is this?

Here is the PHP script

$ip = $argv[1];
if  ($ip == "192.168.1.4") {
     return true;
}

However, the bash variable version is not storing true it is storing the ip address

whatitis2
  • 137
  • 1
  • 3
  • Can you show us the `bash` code? – Andrei Lupuleasa Apr 11 '19 at 16:54
  • The bash code is the first code section – whatitis2 Apr 11 '19 at 17:00
  • The command substitution returns whatever your `php` script *prints,* not what it `return`s. Bash doesn't have "true" or "false" anyway, only string vartiables (though a return code of 0 signifies success to the flow control statements `if`, `while`, and `until`, so you could say `if php "$ip"; then echo PHP said yes; fi` – tripleee Apr 11 '19 at 17:06
  • Also tangentially https://stackoverflow.com/questions/17336915/return-value-in-a-bash-function and https://stackoverflow.com/questions/15013481/in-bash-how-to-store-a-return-value-in-a-variable – tripleee Apr 11 '19 at 17:08
  • I got it working now, however, the bash script is printing the variable with multiple new lines. Why is this? – whatitis2 Apr 11 '19 at 17:29
  • @MonkeyZeus those aren't single quotes, they're backticks – miken32 Apr 11 '19 at 18:23

1 Answers1

1

Use echo instead of return in PHP:

<?php
$ip = $argv[1];
if($ip == "192.168.1.4"){
   echo 1;
}
?>

Bash:

ip="192.168.1.4"
version=`/usr/bin/php -f checkVer.php $ip`
echo $version

Result:

1
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Saleh7
  • 54
  • 3
  • This works, but for some reason it is returning a space before the characters from the variable. So if my version is equal to a 0 it will put a space before the 0. If I use echo "$version" | xargs then it will get rid of the space but I need to store that in a variable somehow instead of echo. I want to store without the space as a variable. Is this possible? – whatitis2 Apr 11 '19 at 18:08