[Linux] Share environment variables with root user

Problem

There are some environment variabels (e.g. http_proxy) set for current user on Ubuntu 20.4, but when running some commands with sudo (like sudo apt update), those environment variables are not available anymore.

Solution

  1. sudo -E

If you are running commands manually, it’s possible to preserve evn setting by adding -E option.

1
sudo -E apt update
  1. sudo visudo

Using option -E may not work in the cases that the commands with sudo are run in script. To make the specific environment settings shared with sudo, it can be configured with visudo.

Using following command:

1
sudo visudo

In opened nano editor, find the line begins with Defaults env_keep, modify it as following to make http_proxy and https_proxy settings be keeped when running commands using sudo:

Defaults        env_keep += "https_proxy http_proxy"

Then, when running sudo apt update, those proxy env variables will kept.