Ubuntu – access the originating $USER variable from within a script run with `sudo`

bashcommand lineenvironment-variablessudo

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?

Best Answer

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

Related Question