How can I correctly import the environment from a subcommand into Perl?

When importing an environment from a subcommand, I want to add all the environment variables exported from the bash script to the hash. When program starts, it will set some variables and export them. I would like to save these variables in a Perl script for later versions. However, I do not want to use the bash functions defined in the subcommand. I currently 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 with initial () is safe. Bonus points for processing new lines in environment variables, which I just close my eyes to right now.

+2
source share
3 answers

I assume that the environment variables after program did not do the same as the environment passed to it (which you can find in %ENV , as described in jeje's answer .

I am in no way aware of bash, so I am going to turn to part of the question about parsing env output.

 #!/usr/bin/perl use strict; use warnings; use autodie qw( open close ); $ENV{WACKO} = "test\nstring\nwith\nnewlines\n\n"; my %SUBENV; open my $env_h, '-|', 'env'; my $var; while ( my $line = <$env_h> ) { chomp $line; if ( my ($this_var, $this_val) = $line =~ /^([^=]+)=(.+)$/ ) { if ( $this_val =~ /^\Q()\E/ ) { $var = q{}; next; } $var = $this_var; $SUBENV{ $var } = $this_val; } elsif ( $var ) { $SUBENV{ $var } .= "\n$line"; } } use Data::Dumper; print Dumper \%SUBENV; 
+1
source

What do you want: Shell-EnvImporter

Example:

  use Shell::EnvImporter; # Import environment variables exported from a shell script my $sourcer = Shell::EnvImporter->new( file => $filename, ); my $result = $sourcer->run() or die "Run failed: $@ "; 
+5
source

This should be good for getting all environment variables.

 for(`program; env`){ if( /^([^=]+)=(.*)$/ ) { $hash{$1} = $2; } } 

If you want to start from scratch, this might work better.

 for(`env -i bash -c "program; env"`){ next if /\(\)/; if( /^([^=]+)=(.*)$/ ) { $hash{$1} = $2; } } 

env -i forces his subcommand to start from scratch.

It calls bash with the -c argument and commands to run. We must do this, because otherwise the second env will not get the environment variables from the program.

0
source

All Articles