2

I want to pass variables from bash to php in 1 script. I know it's possible with 2 files and $argv in the php, but I would really like to put the script in 1 file. This is what i got now:

#!/bin/bash
echo "This is bash"
export VAR="blabla"

/usr/bin/php << EOF
<?php

echo getenv("VAR");

?>
EOF

which works fine. But there is one problem: i can't seem to store the getenv in a variable.

#!/bin/bash
echo "This is bash"
export VAR="blabla"

/usr/bin/php << EOF
<?php

$var = getenv("VAR");
echo $var;

?>
EOF

Gives me this error: PHP Parse error: syntax error, unexpected '=' in - on line 3

I get the same error if i even try to define a basic variable like $var = "hello";

4 Answers 4

5

Your problem is that both bash and php use the dollar sign for variables. When you say this in your heredoc:

$var = getenv("VAR");

bash tried to replace $var with the value of the shell variable var and that's probably empty; the result is that PHP sees something like this:

<?php

= getenv("VAR");
echo ;

?>

Hence the "unexpected '='" error.

Try escaping the dollar signs in your PHP:

#!/bin/bash
echo "This is bash"
export VAR="blabla"

/usr/bin/php << EOF
<?php

\$var = getenv("VAR");
echo \$var;

?>
EOF

A bash heredoc evaluates variables just like a double quoted string.

Sign up to request clarification or add additional context in comments.

Comments

2

If you prevent the shell from interpreting the PHP script, quote the delimiter for your here doc:

/usr/bin/php << 'EOF'
<?php $var = getenv("VAR"); echo $var; ?>
EOF

1 Comment

Yes, i think this is the easiest solution. Thanks!
1

You've ran into one pitfall that comes with the way you want to tackle things, which is put two scripts in one file, one for Bash, the other one for PHP. The problem is that the $var is interpreted by the shell, leaving PHP with = getenv("VAR"); where a statement is expected, hence the syntax error.

Another thing is that you don't need to pull the VAR from the env as long as you keep both scripts in one file (which I think is a bad idea to start with).

Here's how you can to it (not tested):

#!/bin/bash
echo "This is bash"
VAR="blabla" # normal variable, no need to export

/usr/bin/php << EOF
<?php
\$var = "$VAR"; # access variable
echo \$var;
EOF

Comments

0

Why simply not use STDIN:

echo lala.txt | php -r '$line = trim(fgets(STDIN))if(is_file($line)){echo "1";}else{echo "0";}'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.