Environment variable does not seem to work in sudo

environment-variablessudo

I use apt behind a firewall, so I specify a proxy in the http_proxy environment variable.

What I have done is added the following line to both .profile and .bashrc (for good measure) of the root user:

export http_proxy=http://proxyserver:8080

When I do the following, it prints the value of the proxy correctly:

sudo echo $http_proxy

However, when I call sudo apt-get update, it does not seem to see the http_proxy variable as the root user.

Only when I su to root, apt-get works as expected, through the proxy, so it obviously sees the variable.

So my question is, as above, why does sudo apt-get not see the variable?

UPDATE I have just learned that when I call sudo echo, it echoes the value of the variable set in the current user's profile. But even so, why does sudo apt-get not use that variable value?

Best Answer

It doesn't "not seem to work" in the case of sudo apt-get, it seems to work when you do sudo echo $http_proxy.

When you enter a shell command, it globs and expands all variables and aliases before it executes.

So sudo echo $http_proxy becomes sudo echo http://proxyserver:8080 which goes through fine.

The reason $http_proxy isn't seen by apt-get is because sudo clears all environment variables except the ones explicitly whitelisted in /etc/sudoers with the env_keep directive.

More information on how to manipulate the way sudo handles environment variables (or rather, how it usually doesn't) can be found in man sudoers.

Related Question