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?

link|improve this question

60% accept rate
feedback

2 Answers

up vote 3 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.

link|improve this answer
That outputs $HOME (without expansion) – fish 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 :) – fish Oct 20 '11 at 11:39
feedback

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

Your Answer

 
or
required, but never shown

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