[英]Run PHP function inside Bash (and keep the return in a bash variable)
I am trying to run a PHP function inside Bash... but it is not working.我正在尝试在 Bash 内运行 PHP function ... 但它不起作用。
#! /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() function 仅用于说明 ZD574D4BB40C84861791A6949A 操作。
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?有任何想法吗?
php_cwd=`/usr/bin/php << 'EOF'
<?php echo getcwd(); ?>
EOF`
echo "$php_cwd" # Or do something else with it
PHP_OUT=`php -r 'echo phpinfo();'`
echo $PHP_OUT;
Alternatively:或者:
php_cwd = `php -r 'echo getcwd();'`
replace the getcwd();替换 getcwd(); call with your php code as necessary.
必要时使用您的 php 代码致电。
EDIT: ninja'd by David Chan.编辑:大卫陈的忍者。
This is how you can inline PHP commands within the shell ie *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
Use '-R' of php command line.使用 php 命令行的“-R”。 It has a build-in variable that reads inputs.
它有一个读取输入的内置变量。
VAR='/$#'
php_cwd=$(echo $VAR | php -R 'echo preg_quote($argn);')
echo $php_cwd
This is what worked for me:这对我有用:
VAR='/$#'
php_cwd=`/usr/bin/php << EOF
<?php echo preg_quote("$VAR"); ?>
EOF`
echo "$php_cwd"
I have a question - why don't you use functions to print current working directory in bash?我有一个问题 - 为什么不使用函数来打印 bash 中的当前工作目录? Like:
喜欢:
#!/bin/bash
pwd # prints current working directory.
Or或者
#!/bin/bash
variable=`pwd`
echo $variable
Edited : Code above changed to be working without problems.编辑:上面的代码更改为可以正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.