Bash – User name before sudo

bashsudouser-accounts

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?

Best Answer

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