LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Use bash variable in bash call to php function? (https://www.linuxquestions.org/questions/programming-9/use-bash-variable-in-bash-call-to-php-function-4175682604/)

buddy1234567 09-23-2020 10:42 PM

Use bash variable in bash call to php function?
 
Here is the situation:

I have a php script called testAddTwoNums-sol.php with a function called Calculator:

Code:

<?php
//Add two numbers together
function Calculator($x, $y, $op) {
    if($op == '+') {
        $result = $x + $y;
    }
}

I'm attempting to pass values generated in bash to Calculator() like so:

Code:

X=$[RANDOM%10+1]
Y=$[RANDOM%20+10]

# Addition
result=$(php -r "require 'testAddTwoNums-sol.php'; Calculator("X","Y",'+');")

but it doesn't work. I get an error saying 'Warning: Use of undefined constant X - assumed 'X'

How can I pass X and Y from bash using the php cli (as I'm attempting to do above)?

astrogeek 09-23-2020 10:55 PM

Welcome to LQ!

To reference the value of variables in bash, called variable expansion, you must precede the variable name with a $.

So to pass the values of X and Y in your php command you need to refer to them as $X and $Y. If the name would be ambiguous such as being surrounded by other characters then put the names inside curly braces, ${X} and ${Y}.

So you command might become (not tested in actual use, but you get the idea):


Code:

result=$(php -r "require 'testAddTwoNums-sol.php'; Calculator(${X},${Y},'+');")
Give that a try, and good luck!

buddy1234567 09-23-2020 11:38 PM

THanks so much!

That worked perfectly! I gave you a shoutout on StackOverFlow :).

astrogeek 09-24-2020 02:15 AM

You are welcome!

boughtonp 09-24-2020 07:34 AM


 
I assume this is a simplified example of a slightly different problem, because:
1) PHP can generate random numbers without Bash.
2) Bash can do basic integer arithmetic without PHP.



All times are GMT -5. The time now is 08:24 PM.