在 Bash 中运行 PHP 函数(并将返回值保留在 bash 变量中)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6231991/
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 00:07:05  来源:igfitidea点击:

Run PHP function inside Bash (and keep the return in a bash variable)

bashphp

提问by Roger

I am trying to run a PHP function inside Bash... but it is not working.

我正在尝试在 Bash 中运行一个 PHP 函数......但它不起作用。

#! /bin/bash

/usr/bin/php << 'EOF'
<?php echo getcwd(); ?>
EOF

In the reality, I needed to keep the return value in a bash variable... By the way, I am using the php's getcwd() function only to illustrate the bash operation.

在现实中,我需要将返回值保留在bash变量中......顺便说一下,我使用php的getcwd()函数只是为了说明bash操作。

UPDATE:Is there a way to pass a variable?

更新:有没有办法传递变量?

VAR='/$#'
php_cwd=`/usr/bin/php << 'EOF'
<?php echo preg_quote($VAR); ?>
EOF`
echo "$php_cwd"

Any ideas?

有任何想法吗?

回答by phihag

php_cwd=`/usr/bin/php << 'EOF'
<?php echo getcwd(); ?>
EOF`
echo "$php_cwd" # Or do something else with it

回答by David Chan

PHP_OUT=`php -r 'echo phpinfo();'`
echo $PHP_OUT;

回答by damianb

Alternatively:

或者:

php_cwd = `php -r 'echo getcwd();'`

replace the getcwd(); call with your php code as necessary.

替换 getcwd(); 根据需要使用您的 php 代码调用。

EDIT: ninja'd by David Chan.

编辑:由大卫陈忍者。

回答by evandrix

This is how you can inline PHP commands within the shell i.e. *sh:

这是在 shell 中内联 PHP 命令的方法,即 *sh:

#!/bin/bash

export VAR="variable_value"
php_out=$(php << 'EOF'
<?
    echo getenv("VAR"); //input
?>
EOF)
>&2 echo "php_out: $php_out"; #output

回答by Shouguang Cao

Use '-R' of php command line. It has a build-in variable that reads inputs.

使用 '-R' 的 php 命令行。它有一个读取输入的内置变量。

VAR='/$#'
php_cwd=$(echo $VAR | php -R 'echo preg_quote($argn);')
echo $php_cwd

回答by Roger

This is what worked for me:

这对我有用:

VAR='/$#'
php_cwd=`/usr/bin/php << EOF
<?php echo preg_quote("$VAR"); ?>
EOF`
echo "$php_cwd"

回答by koressak

I have a question - why don't you use functions to print current working directory in bash? Like:

我有一个问题 - 为什么不使用函数在 bash 中打印当前工作目录?喜欢:

#!/bin/bash
pwd # prints current working directory.

Or

或者

#!/bin/bash
variable=`pwd`
echo $variable

Edited: Code above changed to be working without problems.

编辑:上面的代码更改为可以正常工作。