Can I access the originating $USER variable from within a script run with `sudo`?
Use the SUDO_USER
environment variable instead of USER
.
sudo
places the name of the user who ran it in the SUDO_USER
environment variable:
ek@Io:~$ sudo sh -c 'echo $USER'
[sudo] password for ek:
root
ek@Io:~$ sudo sh -c 'echo $SUDO_USER'
ek
So you can simply replace $USER
with $SUDO_USER
in your script:
echo $SUDO_USER
Further Reading
man sudo
, in the section on "ENVIRONMENT":SUDO_USER Set to the login name of the user who invoked sudo.
The manpage also describes some other related environment variables defined by
sudo
that may come in handy, such asSUDO_UID
andSUDO_GID
Getting $USER inside shell script when running with sudo?