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

Amedee Van Gasse amedee at
Tue Apr 7 08:05:04 UTC 2009

On Tue, April 7, 2009 02:57, Arch Willingham wrote:
> How do I return the name of the user in a script even if it is fired off
> by SUDO? In other words, if my script has these two lines:
> echo ${USERNAME} echo ${USER}
> If I run it normally when logged in a user named wareagle, it prints out:
> wareagle wareagle
> But if I run it via sudo, it prints out:
> root root
> I need to be able to know the name of the currently logged in user even
> if the script is run by sudo?

>From the man page:


    The -P (preserve group vector) option causes sudo to preserve the
invoking user's group vector unaltered. By default, sudo will
initialize the group vector to the list of groups the target user is
in. The real and effective group IDs, however, are still set to match
the target user.

I have not tested it. Please try it and let us know what happens.


More information about the ubuntu-users mailing list