I’m experiencing a strange behavior related to environment variable preservation with sudo on macOS(15.2): sudo -E doesn't preserve the environment variable PERL5LIB.
Reproduction Steps
Set an environment variable in the shell:
export PERL5LIB=foo. The commandenv | grep PERL5LIBoutputs as expected:PERL5LIB=foo.However, the command
sudo -E env | grep PERL5LIB, returns nothing. In contrast, this works:sudo --preserve-env=PERL5LIB env | grep PERL5LIB. It successfully preservesPERL5LIB.
This is confusing because I expected sudo -E to preserve all environment variables from the invoking shell, including PERL5LIB. But clearly, it’s not working that way for this particular variable.
Question
- Why is
PERL5LIBnot preserved bysudo -Eon macOS? - Is this behavior specific to
PERL5LIB, or does it affect other variables as well? - What is the recommended, reliable way to ensure that
PERL5LIBis preserved when using sudo?
/etc/sudoers, or any files in/etc/sudoers.d, contain aenv_delete+=PERL5LIBstatement? I don't use macOS to confirm, but the answers in How can I keep all environment vars for a specific command in sudo? might help.sudo sudo -V/etc/sudoers. The only file under/etc/sudoers.disamphetamine_PowerProtect, which has nothing to do withsudocommand. However, as @StéphaneChazelas pointed out, runningsudo sudo -Vreveals a list of environment variables to remove, andPERL5LIBis included in that list.amphetamine_PowerProtectunder/etc/sudoers.dis indeed part of thesudoconfiguration, it only configures passwordless access for a couple of specific commands. It doesn’t affect the general behavior ofsudoitself, such as how environment variables are handled — which is the focus of my question.