In the manpage of sudo I found the -H option, but I don't seem to understand how it works. The manpage says:

The -H ( HOME ) option sets the HOME environment variable to the homedir of the target user (root by default) as specified in passwd(5).

In my understanding, the following should not happen:

root $ sudo -u sztomi -H echo $HOME

But instead it should output /home/sztomi which is the home directory of the user sztomi.

How can I do this right?


You haven't quoted $HOME, so the current value is being substituted prior to the execution of the sudo command. Surround it with single quotes (').


As we noticed (see comments), sudo does not call a subshell to start the given command (therefore there is no shell expanding $HOME). The revised command would be:

 sudo -u sztomi -H bash -c 'echo $HOME'

Explained: sudo switches the user ID and then calls a bash shell which in turn takes the echo $HOME, substitutes the variable HOME by its value and finally performs the echo command.

Note that calling the subshell is only neccessary in this example to get the variable HOME substituted after sudo switched the user ID. It is not neccessary if you just want to start a single program without variable substitution in the target environment.

  • That outputs $HOME (without expansion) – Tamás Szelei Oct 20 '11 at 10:21
  • 1
    hmm - sounds like there is no intermediate shell process. Try: sudo -u sztomi -H bash -c 'echo $HOME' – ktf Oct 20 '11 at 10:25
  • Yep, that works. Could it be that it's the shell dash and not bash? Anyway, please add this to the answer so I can accept it :) – Tamás Szelei Oct 20 '11 at 11:39

You should be able to use ~sztomi to get the environment variable.

For example, this will list the contents to sztomi's home dir.

sudo -u sztomi ls ~sztomi
  • If only it worked with ~$username... – user1686 Oct 20 '11 at 13:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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