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?
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
.Defaults env_reset
in/etc/sudoers
will reset root'sPATH
defined by/etc/environment
.You could modify it to
Defaults !env_reset
to disable resetting or add: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'.
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 passPATH
and proxy environment variables.Command:
And you can add it as an alias (add this
.bashrc
,.bash_aliases
or.zshrc
etc).Example of my alias:
Be mindful that this obviously reduces the security of sudo.