Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

It seems when sudoing down that using sudo -u $user that the environment of root is still being used. How can I make sudo use the users environment? as a special note not all users that I will be using this on have login shells.

share|improve this question
Define 'environment'. # whoami => root # sudo -u user whoami => user – alex Nov 26 '10 at 6:54
@alex I figure sudo -u user is analogous to su user to switch the env in su you have to use su - user – xenoterracide Nov 26 '10 at 8:16
But what do you mean with "the user's environment" if the user doesn't have a login shell? – Thomas Themel Nov 26 '10 at 12:07
@Thomas users can run programs even if they can't shell in... I believe -u also ignores groups... I tried something from root (using sudo -u down) and it worked, apparently it didn't for the user... so I have to make sure I'm running commands in a way that would have all there limitations and environmental issues. – xenoterracide Nov 26 '10 at 15:29
up vote 17 down vote accepted

Try sudo -i -u $user

gerald@book:~$ env |grep HOME
gerald@book:~$ sudo -u ubuntu env |grep HOME
gerald@book:~$ sudo -i -u ubuntu env |grep HOME
share|improve this answer
unfortunately doesn't work if they don't have a shell in /etc/passwd :( but it'll do I guess... – xenoterracide Dec 3 '10 at 10:39
Looking at the man page, it seems that -E is the one that preserves the environment, i.e. all the environment variables etc are there, although it still doesn't set PATH and LD_LIBRARY_PATH to the calling user's. – Shahbaz Jun 17 '13 at 15:22
$SUDO_USER can be used – Rahul Patil Oct 26 '15 at 8:42

man sudoers on Debian mentions another possibility. Not sure which way around you want, but your question sounds like you would want to have the env_reset option from /etc/sudoers - the opposite is basically the env_keep list. In order to set the proper HOME you can use the -H option to sudo directly or, again in sudoers, with the always_set_home option.

Alternatively you could use env_file to specify an exact environment you want to pass. However, I think it is best if you check out the env_* options from man sudoers, because /etc/sudoers controls it all and that's the point to turn to.

Here's part of the context in which I use env_reset inside my sudoers file:

Defaults        !lecture
Defaults        env_reset
Defaults        syslog=auth
Defaults        log_year
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.