如何在bash中从php文件读取变量

Kar*_*enV 5 bash php

如何在 Bash 中从 PHP 脚本导出变量?

我正在编写一个 Bash 脚本来从config.php每个网站的文件中读取数据库名称,然后从备份存储库导入数据库。我尝试使用source config.php,但它似乎无法识别 PHP 变量。

任何帮助,将不胜感激。

rub*_*ils 0

一个非常简化的版本如下:

2 行config.php

cat config.php
$variable1 = 'foo with bar';
$variable1 = 'foo2 with bar2';
Run Code Online (Sandbox Code Playgroud)

将 Bash 设置为in$variable1的最后一个匹配实例,以防万一它已被重置。如果你想将其更改为第一个匹配项,只需在以下代码中更改为:$variable1config.phptail -1head -1

variable1="$(grep -oE '\$variable1 = .*;' config.php | tail -1 | sed 's/$variable1 = //g;s/;//g')"
Run Code Online (Sandbox Code Playgroud)

通过以下方式确认 Bash 变量echo

echo "$variable1"
'foo2 with bar2'
Run Code Online (Sandbox Code Playgroud)

请注意,这主要适用于字符串。有许多类型的 PHP 变量无法直接转换为 Bash 变量。上面的代码将$variable1获取config.php. 就像我说的,如果该变量已设置多次,您可以通过切换headtail在设置该变量的 Bash 命令中设置为第一个值或最后一个值。