58

To create persistent environment variables, I add the script file to /etc/profile.d directory, for example:

# my script
export MY_VAR=var_value

This works properly for current user:

alex@alex-64:~$ echo $MY_VAR
var_value

Now I need the same environment variables for the root user, but /etc/profile.d script doesn't work for root:

alex@alex-64:~$ echo $MY_VAR
var_value
alex@alex-64:~$ sudo su
root@alex-64:/home/alex# echo $MY_VAR

root@alex-64:/home/alex# 

How can I set the same variables for the root?

1

4 Answers 4

65

sudo does not normally preserve local environment variables. You should use it with the -E switch to do so, i.e. sudo -E su will preserve $MYVAR for root.

Alternatively, to create persistent variables that are truly system-wide, you should set them in /etc/environment.

4
  • 21
    Does not work, /etc/environemnt variables are not set for sudo Jan 24, 2015 at 13:49
  • 4
    @FredericYesidPeñaSánchez it did for me on CentOS. You don't script in there, you just do simple assignments on each line, i.e. FOO=bar
    – iamyojimbo
    Oct 5, 2016 at 22:25
  • 2
    Thanks, worked. /etc/environment values were available as root after restarting my terminal (not before)
    – dutoitns
    Jan 16, 2020 at 11:32
  • Worked for me right away on Ubuntu 20.04
    – J. Gwinner
    Sep 20, 2022 at 1:12
10

Defaults env_reset in /etc/sudoers will reset root's PATH defined by /etc/environment.

You could modify it to Defaults !env_reset to disable resetting or add:

Defaults secure_path="my/custom/path:/bin:/usr/bin:/usr/local/bin:/sbin:/usr/sbin
1
  • If I want to use the second solution(means add path to secure_path), what is key?! path is just value. I want to add ANDROID_NDK to environment variables for root. So for now, I just using the first one(!env_reset).Thanks.
    – Dr.jacky
    Dec 6, 2015 at 6:07
10

Like the process you define your own environment variable, for example by editing '~/.bashrc', you can define root's environment variable by editing '/root/.bashrc'.

2

You can pass environment variables using env flag. I always need to get around proxies and this is a constant issue for me. Especially when you need to pass PATH and proxy environment variables.

Command:

sudo env "ENV=$ENV1" "ENV2=$ENV2" [command]

And you can add it as an alias (add this .bashrc, .bash_aliases or .zshrc etc).

Example of my alias:

alias psudo='sudo env "PATH=$PATH" "HTTP_PROXY=$HTTP_PROXY" "HTTPS_PROXY=$HTTPS_PROXY" "http_proxy=$http_proxy" "https_proxy=$http_proxy"'

Be mindful that this obviously reduces the security of sudo.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .