Ubuntu – How to set persistent environment variables for root


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

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
alex@alex-64:~$ sudo su
root@alex-64:/home/alex# echo $MY_VAR


How can I set the same variables for the root?

Best Answer

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.