running as root but $USER returning regular user?

So I was going to run a shell script but it’s not working since it needs to be run as root. Thing is I’m logged in as root using the su command.

how is this possible?

root@polo-E15301:/home/polo/Downloads# echo $USER
polo      <<<---- regular user
root@polo-E15301:/home/polo/Downloads# whoami
root@polo-E15301:/home/polo/Downloads# echo $UID
Asked By: guu1


When suing to root specifically, su doesn’t set USER unless a login shell is requested; man su says

For backward compatibility, su defaults to not change the current
directory and to only set the environment variables HOME and
SHELL (plus USER and LOGNAME if the target user is not root). It
is recommended to always use the --login option (instead of its
shortcut -) to avoid side effects caused by mixing environments.

If you use su --login you’ll find USER is set to root.

In shell scripts, testing for root privileges should be done using a tool like id rather than relying on environment variables. See also Who sets $USER and $USERNAME environment variables?

Answered By: Stephen Kitt
Categories: Answers Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.