http://www.perlmonks.org?node_id=33634


in reply to Get default login environment

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.