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 ofUSER
.sudo
places the name of the user who ran it in theSUDO_USER
environment variable:So you can simply replace
$USER
with$SUDO_USER
in your script:Further Reading
man sudo
, in the section on "ENVIRONMENT":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?