I got a script rquiring sudo, but the script must set parameters according to the original user, such as:

chown "${USER}:${USER}" dir

If I set it under sudo, I just end up with "chmod root:root", which doesn't help.

How can I do that ?

link|improve this question

50% accept rate
feedback

2 Answers

up vote 6 down vote accepted

The environment variable SUDO_USER should work as a replacement for USER.

Since you are setting the ownership to USER:USER I assume there is always a group with the same name as the user? A more strict solution might otherwise be to use SUDO_UID and SUDO_GID.

Two possible solutions would then be:

chown "${SUDO_USER}:${SUDO_USER}" dir

or

chown "${SUDO_UID}:${SUDO_GID}" dir
link|improve this answer
Nice anwser, with the solution AND some additional infos. – e-satis Nov 30 '09 at 13:43
Using the UID/GID is the best solution, as it is possible to have multiple UIDs with the same username. – duffbeer703 Nov 30 '09 at 13:46
feedback

You can use the SUDO_USER variable:

sudo bash -c 'echo $SUDO_USER'

From the sudo man page:

if sudo is run by root and the SUDO_USER environment variable is set, sudo will use this value to determine who the actual user is. This can be used by a user to log commands through sudo even when a root shell has been invoked.

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

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