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

6,109

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

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.

Share:
6,109

Related videos on Youtube

Christopher
Author by

Christopher

Ubuntu fan since Fiesty.

Updated on September 18, 2022

Comments

  • Christopher
    Christopher over 1 year

    A weird question, I know. Here's the script:

    echo $USER
    

    Here's the command I use to run it:

    sudo ./myscript.sh
    

    Right now it prints "root" but I want it to print jon, my username. Is there a way to do that by changing the script, and not the command?