How to return user name in a script even if run by SUDO?

Sundar Nagarajan sundar.personal at
Wed Apr 8 05:55:41 UTC 2009

Smoot Carl-Mitchell wrote:
> On Tue, 2009-04-07 at 19:07 +0530, kapil singh kushwah wrote:
>> Hello ,
>> It is working fine. I guess you did it
>> after login as a root.
>> I am getting :
>> common at common-laptop:~$ echo ${USER}
>> common
>> common at common-laptop:~$ sudo echo ${USER}
>> common
>> common at common-laptop:~$ 
> Your conclusion is incorrect.  The ${USER} environment variable is being
> interpolated by the parent shell and *not* sudo.  As per the sudo man
> page, the SUDO_USER environment variable is available to tell you who
> invoked the command.  To use this in general in a bash script use a
> function like
> function invoking_user {
> }
> which sets the INVOKING_USER environment variable.  You can use this to
> get the "real" user name of the user who ran the command.  It appears
> sudo is careful about setting SUDO_USER to the real username instead of
> using the USER environment variable which can be spoofed.

why not just use ${SUDO_USER:-$USER}
will return ${SUDO_USER} if set (when inside a sudo shell) and return 
${USER} otherwise (not inside a sudo shell).

More information about the ubuntu-users mailing list