如何在 Perl 中运行子命令正确导入环境?
在从子命令导入环境时,我想将从 bash 脚本导出的所有环境变量添加到哈希中。 当program
运行时,它将设置一些变量并导出它们。 我想将这些变量保存在 Perl 脚本中供以后使用。 但是我不想采用子命令中定义的 bash 函数。 目前,我有一个类似的问题:
foreach (`program; env`)
{
next if /^\(\)/;
my ($a, $b) = split("=", $_);
if( /^(\w+)=(.*)$/ ) {
$hash{$1} = $2;
}
}
有更好的方法吗? 我不确定匹配初始 () 是否安全。 处理环境变量中的换行符的奖励积分,我现在只是闭上眼睛。
In importing the environment from a subcommand, I want to add all environment variables exported from a bash script to a hash. When program
gets run, it will set up some variables and export them. I'd like to save those variables in the Perl script for later. However I don't want to take the bash functions defined in the subcommand. Currently, I have a block like:
foreach (`program; env`)
{
next if /^\(\)/;
my ($a, $b) = split("=", $_);
if( /^(\w+)=(.*)$/ ) {
$hash{$1} = $2;
}
}
Is there a better way to do this? I'm not sure if matching the initial () is safe. Bonus points for handling newlines in environment variables, which I'm just closing my eyes for right now.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你想要的就在那里: Shell-EnvImporter
示例:
What you want is there: Shell-EnvImporter
An example:
我假设
program
执行后的环境变量与传递给它的环境不同(您可以在%ENV
中找到,如 jeje的回答。我是我对 bash 一点也不了解,所以我只会解决有关解析
env
输出的问题部分。I am assuming that the environment variables after
program
has executed are not same as the environment passed to it (which you can find in%ENV
as explained in jeje's answer.I am by no means knowledgeable about bash, so I am only going to address the part of the question about parsing the output of
env
.这对于获取所有环境变量应该没问题。
如果您想从头开始,这可能会更好。
env -i
使其子命令从头开始。它使用
-c
参数调用 bash 以及要运行的命令。 我们需要这样做,因为否则第二个env
将无法从程序中获取环境变量。This should be fine for getting all of the environment variables.
If you want to start with a clean slate this might work better.
env -i
makes it's subcommand start off with a clean slate.It calls bash with the
-c
argument, and the commands to run. We need to do that because otherwise the secondenv
wouldn't get the environment variables from the program.