简体   繁体   English

如何在PHP命令(CLI)中传递bash脚本变量值

[英]How to pass bash script variable value in PHP command (CLI)

I need help in passing the Linux bash-script variable to execute the PHP CLI command. 在传递Linux bash-script变量以执行PHP CLI命令时,我需要帮助。

I am working on the bash-script that executes PHP CLI command that gets input variable from the bash-script like folder-path to include a file for accessing a class of the PHP file. 我正在研究执行PHP CLI命令的bash脚本,该命令从bash脚本(如文件夹路径)获取输入变量,以包括用于访问PHP文件类的文件。

But what happens while executing the bash-script is that the variable passed to the PHP CLI-command act as a variable for PHP. 但是在执行bash脚本时发生的是,传递给PHP CLI命令的变量充当PHP的变量。

Below is the sample-code my script 下面是我的脚本的示例代码

file="$folderpath"somefile.php
mage_version=$(php -r 'include "$file";print_r(Mage::getVersionInfo());')

Below is the error I am getting 以下是我得到的错误

PHP Notice:  Undefined variable: file in Command line code on line 1
PHP Warning:  include(): Filename cannot be empty in Command line code on line 1

Bash needs double ( " ) quotes to parse variable, otherwise they will stay $var and so php will read them; Bash需要双引号( " )来解析变量,否则它们将保持$var ,因此php将读取它们;

file="$folderpath"somefile.php
mage_version=$(php -r "include \"${file}\";print_r(Mage::getVersionInfo());")

More inline bash info 更多内联bash信息

If you need a multi line solution, you can do something like: Run PHP function inside Bash (and keep the return in a bash variable) 如果您需要多行解决方案,则可以执行以下操作: 在Bash中运行PHP函数(并将返回值保留在bash变量中)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM