bash 来自bash管道和heredoc的php stdin

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8649131/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 01:13:27  来源:igfitidea点击:

php stdin from bash pipe and heredoc

bashphp

提问by Billy Moon

Can I receive input from both a pipe, and a heredoc, and use them both from within php on the command line.

我可以从管道和 heredoc 接收输入,并在命令行的 php 中使用它们吗?

I want to do something like this:

我想做这样的事情:

bash$ ls -l | php <<'code'
<?php
   echo $piped;
?>
code

Which should return the result of ls -l

哪个应该返回结果 ls -l

Also, can I use php -Rwith heredoc input for php script?

另外,我可以php -R将heredoc输入用于php脚本吗?

回答by Shiplu Mokaddim

Piping

管道

ls -l | php -r 'print_r(file("php://stdin"));'

ls -l | php -r 'print_r(file("php://stdin"));'



Heredoc

赫里多克

$ php <<CODE
<?php
echo "Hello World\n";
?>
CODE
Hello World


Combined

组合

$ ls -l | php <<'CODE'
<?php
$f = file("php://stdin");
foreach($f as $k=>$v){
echo "[$k]=>$v";
}
?>
Program Finished
CODE

[0]=><?php
[1]=>$f = file("php://stdin");
[2]=>foreach($f as $k=>$v){
[3]=>echo "[$k]=>$v";
[4]=>}
[5]=>?>
[6]=>Program Finished
Program Finished

Note: When you use Here Documentsfor phpcommand the newly added phpcodes overrides the previous stdin

注意:当您使用Here Documents作为php命令时,新添加的php代码会覆盖之前的代码stdin

回答by hakre

Regarding the -Rpart of the question:

关于问题的-R一部分:

-R/ --process-code

PHP code to execute for every input line. Added in PHP 5.

There are two special variables available in this mode: $argnand $argi. $argnwill contain the line PHP is processing at that moment, while $argiwill contain the line number. Docs

-R/ --process-code

为每个输入行执行的 PHP 代码。在 PHP 5 中添加。

在此模式下有两个特殊变量可用:$argn$argi$argn将包含当时 PHP 正在处理的行,而$argi将包含行号。文档

If I understood your question right, you're looking for the $argnvariable. Heredoc should be support by your bash.

如果我正确理解您的问题,那么您正在寻找$argn变量。Heredoc 应该得到你的 bash 的支持。

Edit:Err, just invoke with the value over multiple lines:

编辑:Err,只需在多行中调用该值:

$ ls -l | php -R '
printf("#%02d: %s\n", $argi, $argn);
'

(I think it's easier to use the single quote for the switch)

(我认为在 switch 中使用单引号更容易)