Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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
/root

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

How can I do this right?

share|improve this question
add comment

2 Answers

up vote 4 down vote accepted

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 (').


EDIT:

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.

share|improve this answer
    
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
add comment

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
share|improve this answer
    
If only it worked with ~$username... –  grawity Oct 20 '11 at 13:01
add comment

Your Answer

 
discard

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.