After looking at exec's documentation I noticed a more general way to do this. You call sh, lying to it about its name. Here is a slightly more general function, does the same thing as above but does not assume you are running bash as your default shell:
sub get_login_env {
local %ENV;
my $shell = shift || (getpwuid($<))[8];
my $env = `echo env | perl -e 'exec {"$shell"} -sh'`;
if (wantarray) {
$env =~ s/\\(.)/$1/gs;
return map {split /=/, $_, 2} map {split /\n/, $_} $env;
}
else {
return $env;
}
}
And since someone asked, the reason for localizing %ENV was to clear the environment before calling the login shell. I may trust the login environment to have a sane environment, but I won't trust my current environment to be clean! :-)
This should work on virtually any *nix with virtually any valid shell, and you can choose the shell to be an argument or take the current shell you use (your choice).
Update: (Much later.) Hue-Bond pointed out that the missing | in the grandchild is missing here as well. Fixed.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|