To answer this question correctly, I need to know a little more.
- Is it possible to run a shell script from within a perl script?
- Do all forms assign
export VAR=value to variables (i.e., with fixed assignments, without variable substitutions or command substitutions)? - Does the shell script use anything else but assign variables?
Depending on the answers to them, there are various options for complexity.
Thanks for clarifying. Ok, here's how to do it. Besides assigning variables, your script has no side effects. This allows you to run the script from within perl. How to find out which variables are exported to a script? We could try to parse the shell of the script, but this is not a Unix way of using tools that do something well, and combine them. Instead, we use the shell export -p command to declare all exported variables and their values. To find only the variables actually set by the script, and not all the other noises, the script is run in a clean environment using env -i , another underrated POSIX jewel.
Putting it all together:
#!/usr/bin/env perl use strict; use warnings; my @cmd = ( "env", "-i", "PATH=$ENV{PATH}", "sh", "-c", ". ./myshell.sh; export -p" ); open (my $SCRIPT, '-|', @cmd) or die; while (<$SCRIPT>) { next unless /^export ([^=]*)=(.*)/; print "\$ENV{$1} = '$2'\n"; $ENV{$1} = $2; } close $SCRIPT;
Notes:
- You need to go into
env -i whole environment your myshell.sh needs, for example. PATH - Shells usually export the
PWD variable; if you do not want this in your Perl ENV hash, add next if $1 eq 'PWD'; after the first next .
That should do the trick. Let me know if this works.
See also:
source share