Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep environment variables when using sudo

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.

like image 496
Ahmed Aswani Avatar asked Dec 26 '11 06:12

Ahmed Aswani


People also ask

What is sudo environment variables?

by admin. su and sudo allow to execute commands or shell with a different user. Depending on how they are invoked the environment variables can change, causing different command results. Both “su” and “sudo” allow to execute commands on behalf of other user.

How do I set environment variables permanently?

You can set an environment variable permanently by placing an export command in your Bash shell's startup script " ~/. bashrc " (or "~/. bash_profile ", or " ~/. profile ") of your home directory; or " /etc/profile " for system-wide operations.

How do I permanently set environment variables in Ubuntu?

To summarize, if you want to set it in current session, then you can do so from the terminal. If you want it to be permanent for a given user, then set it in . bashrc file for that user. If you want to set the variable globally for all users, on a permanent basis, then add it to /etc/environment file.


2 Answers

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. 
like image 187
Employed Russian Avatar answered Sep 30 '22 06:09

Employed Russian


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" 
like image 43
7 revs, 5 users 41% Avatar answered Sep 30 '22 08:09

7 revs, 5 users 41%