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

Smoot Carl-Mitchell smoot at tic.com
Tue Apr 7 16:15:36 UTC 2009


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 {
  export INVOKING_USER=$USER
  [ "$SUDO_USER" ] && INVOKING_USER=$SUDO_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.
-- 
Smoot Carl-Mitchell
Computer Systems and
Network Consultant
smoot at tic.com
+1 480 922 7313
cell: +1 602 421 9005




More information about the ubuntu-users mailing list