User name before sudo

6,725

Solution 1

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

Solution 2

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.

Solution 3

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 https://stackoverflow.com/questions/4598001/how-do-you-find-the-original-user-through-multiple-sudo-and-su-commands

Share:
6,725

Related videos on Youtube

e-satis
Author by

e-satis

French Python/Django dev, I like training people too (see decorators, metaclasses and yield) Current favorite stack: jQuery + Boostrap Nginx + Gunicorn MySQL + Redis Took me a while but now I can show off:

Updated on September 17, 2022

Comments

  • e-satis
    e-satis over 1 year

    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?

  • e-satis
    e-satis over 14 years
    Nice anwser, with the solution AND some additional infos.
  • duffbeer703
    duffbeer703 over 14 years
    Using the UID/GID is the best solution, as it is possible to have multiple UIDs with the same username.
  • kerem
    kerem about 9 years
    After running 'sudo su -' the environment variables aren't available, but logname and who am i work.
  • cladmi
    cladmi about 9 years
    You're right, it's not possible to rely on environment variable.
  • cladmi
    cladmi about 8 years
    Found on some host that SUDO_USER can't be overwritten: sudo: sorry, you are not allowed to set the following environment variables: SUDO_USER So it may still be safe, should still verify this.
  • cladmi
    cladmi about 8 years
    It's because my command is set as "NOPASSWD", so it depends on your sudoers configuration via "NOSETENV".
  • Robert
    Robert almost 5 years
    But why sudo echo $SUDO_USER outputs nothing?