是否可以使用PHP CLI引用* .sh文件,并在PHP脚本中访问导出的Env vars? [英] Is it possible to source a *.sh file using PHP CLI and access exported Env vars in the PHP script?

查看:70
本文介绍了是否可以使用PHP CLI引用* .sh文件,并在PHP脚本中访问导出的Env vars?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通常在linux上的一个bash终端中发送一个* .sh文件,这样

I usually source a *.sh file in a bash terminal on linux like this

. ./myscript.sh

在运行命令行PHP脚本之前,我可以使用PHP访问导出的环境变量$ _SERVER超级全局。

before running a command line PHP script so i can access exported environment variables using PHP's $_SERVER super global.

是否可以从PHP脚本本身中获取sh文件,然后访问其导出的变量?

Is it possible to source the sh file from within the PHP script itself to then access the variables it exports?

我已经尝试过各种不成功。我试过

I've tried all sorts with no success. I've tried

system('. ./myscript.sh')
system('sh ./myscript.sh')

exec('. ./myscript.sh')
exec('sh ./myscript.sh')

shell_exec('. ./myscript.sh')
shell_exec('sh ./myscript.sh')

使用这些,导出的vars不会出现在$ _SERVER中。

using these, the exported vars do not appear in $_SERVER.

任何想法?

推荐答案

您的变量不存在,因为它们存在的shell已经退出。您需要从同一个shell中执行PHP以获取其变量。

Your variables aren't available because the shell that they existed in has exited. You need to execute PHP from within the same shell in order to get its vars.

在设置vars之后,编辑myscript.sh以启动PHP脚本:

Either edit myscript.sh to launch the PHP script after setting the vars:

export VAR1=1
export VAR2=2
php -f /path/to/script.php

或者写另一个包装脚本来源文件,然后从同一个shell启动PHP:

Or write another wrapper script that sources your file and then launches PHP from the same shell:

. ./myscript.sh
php -f /path/to/script.php

编辑:或者只是运行这样的脚本:

Or just run your script like this:

. ./myscript.sh && php -f /path/to/script.php

这篇关于是否可以使用PHP CLI引用* .sh文件,并在PHP脚本中访问导出的Env vars?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆