bash 和 php-cli 之间的变量
我想在 1 个脚本中将变量从 bash 传递到 php。我知道 php 中可以有 2 个文件和 $argv,但我真的很想将脚本放在 1 个文件中。这就是我现在得到的:
#!/bin/bash
echo "This is bash"
export VAR="blabla"
/usr/bin/php << EOF
<?php
echo getenv("VAR");
?>
EOF
效果很好。但有一个问题:我似乎无法将 getenv 存储在变量中。
#!/bin/bash
echo "This is bash"
export VAR="blabla"
/usr/bin/php << EOF
<?php
$var = getenv("VAR");
echo $var;
?>
EOF
给我这个错误: PHP 解析错误:语法错误,意外的 '=' in - on line 3
如果我尝试定义像 $var = "hello"; 这样的基本变量,我也会得到同样的错误。
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";
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您的问题是 bash 和 php 都使用美元符号作为变量。当你在heredoc中这样说时:
bash尝试用shell变量
var
的值替换$var
,而这可能是空的;结果是 PHP 看到类似这样的内容:因此出现“意外的 '='” 错误。
尝试在 PHP 中转义美元符号:
bash 定界文档评估变量就像双引号字符串一样。
Your problem is that both bash and php use the dollar sign for variables. When you say this in your heredoc:
bash tried to replace
$var
with the value of the shell variablevar
and that's probably empty; the result is that PHP sees something like this:Hence the "unexpected '='" error.
Try escaping the dollar signs in your PHP:
A bash heredoc evaluates variables just like a double quoted string.
如果您阻止 shell 解释 PHP 脚本,请引用此处文档的分隔符:
If you prevent the shell from interpreting the PHP script, quote the delimiter for your here doc:
您遇到了一个陷阱,该陷阱与您想要解决问题的方式有关,即将两个脚本放入一个文件中,一个用于 Bash,另一个用于 PHP。问题在于
$var
由 shell 解释,使 PHP 在需要语句的地方留下= getenv("VAR");
,因此出现语法错误。另一件事是,只要将两个脚本保存在一个文件中,您就不需要从环境中提取 VAR(我认为从一开始就是一个坏主意)。
以下是您可以使用的方法(未经测试):
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):
为什么不使用 STDIN:
echo lala.txt | php -r '$line = trim(fgets(STDIN))if(is_file($line)){echo "1";}else{echo "0";}'
Why simply not use
STDIN
:echo lala.txt | php -r '$line = trim(fgets(STDIN))if(is_file($line)){echo "1";}else{echo "0";}'