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?
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?
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: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
.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.