How to keep environment variables when using sudo

2018-12-31 06:19发布

When I use any command with sudo the environment variables are not there. For example after setting HTTP_PROXY the command wget works fine without sudo. However if I type sudo wget it says it can't bypass the proxy setting.

4条回答
初与友歌
2楼-- · 2018-12-31 06:22

You can also combine the two env_keep statements in Ahmed Aswani's answer into a single statement like this:

Defaults env_keep += "http_proxy https_proxy"

You should also consider specifying env_keep for only a single command like this:

Defaults!/bin/[your_command] env_keep += "http_proxy https_proxy"

查看更多
柔情千种
3楼-- · 2018-12-31 06:26

The trick is to add environment variables to sudoers file via sudo visudo command and add these lines:

Defaults env_keep += "ftp_proxy http_proxy https_proxy no_proxy"

taken from ArchLinux wiki.

For Ubuntu 14, you need to specify in separate lines as it returns the errors for multi-variable lines:

Defaults  env_keep += "http_proxy"
Defaults  env_keep += "https_proxy"
Defaults  env_keep += "HTTP_PROXY"
Defaults  env_keep += "HTTPS_PROXY"
查看更多
春风洒进眼中
4楼-- · 2018-12-31 06:29

For individual variables you want to make available on a one off basis you can make it part of the command.

sudo http_proxy=$http_proxy wget "http://stackoverflow.com"
查看更多
弹指情弦暗扣
5楼-- · 2018-12-31 06:45

First you need to export HTTP_PROXY. Second, you need to read man sudo carefully, and pay attention to the -E flag. This works:

$ export HTTP_PROXY=foof
$ sudo -E bash -c 'echo $HTTP_PROXY'

Here is the quote from the man page:

-E, --preserve-env
             Indicates to the security policy that the user wishes to preserve their
             existing environment variables.  The security policy may return an error
             if the user does not have permission to preserve the environment.
查看更多
登录 后发表回答