linux - [Solved-4 Solutions] How to keep Environment Variables when using SUDO in Linux ? - ubuntu - red hat - debian - linux server - linux pc



Linux - Problem :

How to keep Environment Variables when using SUDO in Linux ?

Linux - Solution 1:

You need to export HTTP_PROXY.

$ export HTTP_PROXY=foof
$ sudo -E bash -c 'echo $HTTP_PROXY'
click below button to copy the code. By - Linux tutorial - team
-E, --preserve-env
             Indicates to the security policy that the user wishes to reserve their
             existing environment variables.  The security policy may eturn an error
             if the user does not have permission to preserve the environment.
click below button to copy the code. By - Linux tutorial - team

Linux - Solution 2:

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"
click below button to copy the code. By - Linux tutorial - team

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"
click below button to copy the code. By - Linux tutorial - team

Linux - Solution 3:

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

sudo http_proxy=$http_proxy wget "http://wikitechy.com"
click below button to copy the code. By - Linux tutorial - team

Linux - Solution 4:

You can also combine the two env_keep statements into a single statement like this:

Defaults env_keep += "http_proxy https_proxy"
click below button to copy the code. By - Linux tutorial - team

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

Defaults!/bin/[your_command] env_keep += "http_proxy https_proxy"
click below button to copy the code. By - Linux tutorial - team

Related Searches to - linux - linux tutorial - How to keep Environment Variables when using SUDO in Linux ?