Ubuntu: How do I set environment variable for all users even when doing sudo su?



Question:

I created a file named x.sh in the directory /etc/profile.d/ so it should be accessible to all users. I expected when I change the current user in terminal (of logged-in user) using command sudo su other_user, those variable that I set in x.sh file should be accessible but they not. How can I set variables to be accessible as I desired?


Solution:1

/etc/profile (and hence /etc/profile.d) is read for login shells. sudo su other_user does not run a login shell. It is a bad practice, it leaves the environment contaminated with variables from the original user. You should do either of these commands instead:

sudo -iu other_user  sudo su - other_user  

Both of these load /etc/profile because they start login shells, and both start with relatively clean environments.

Ideally, though, the variables should be set in /etc/environment if possible. That file should be read by su, so variables there would be available irrespective of whether a login shell is started. However, that file doesn't support shell syntax, so if you need complex shell code to set your variables, you can't use it.


Solution:2

Following How to permanently set environmental variables · U&L bash will load

/etc/profile  

so that's the right place to add variables effective for all users.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »