Can I access the originating $USER variable from within a script run with `sudo`?

Solution 1:

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 as SUDO_UID and SUDO_GID

  • Getting $USER inside shell script when running with sudo?

Solution 2:

In addition to @Eliah Kagan's answer above, I would like to point out that you can also easily have an expansion which works both if it runs in a sudo context or not:

echo "${SUDO_USER:-$USER}"

This expands to the value of $SUDO_USER by default, but if if that variable is unset or empty, it falls back to the value of $USER.

$ bash -c 'echo "${SUDO_USER:-$USER}"'
bytecommander

$ sudo bash -c 'echo "${SUDO_USER:-$USER}"'
bytecommander

More information about default parameter expansion in Bash can be found e.g. on https://wiki.bash-hackers.org/syntax/pe#use_a_default_value.