Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

I got a script requiring 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.

So how can I get the user name before sudo?

share|improve this question

3 Answers 3

up vote 10 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
share|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

You can use the SUDO_USER variable:

sudo bash -c 'echo $SUDO_USER'

From the sudo man page:

sudo utilizes the following environment variables. The security policy has control over the actual content of the command's environment. [...]

SUDO_UID Set to the user ID of the user who invoked sudo.

SUDO_USER Set to the login name of the user who invoked sudo.

share|improve this answer

SUDO_USER can be overwritten by the user.

 $ SUDO_USER='lala' sudo SUDO_USER='test' printenv | grep USER
 USER=root
 SUDO_USER=test
 USERNAME=root

You should use 'who am i' or 'logname' to get the original username

toto:~$ SUDO_USER='lala' sudo SUDO_USER='test' logname             
toto
toto:~$ SUDO_USER='lala' sudo SUDO_USER='test' who am i
toto   pts/4        Jan 23 15:13 (:0.0)

Coming from http://stackoverflow.com/questions/4598001/how-do-you-find-the-original-user-through-multiple-sudo-and-su-commands

share|improve this answer

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.