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

Arch Willingham arch at tuparks.com
Wed Apr 8 00:13:30 UTC 2009


Thanks!

-----Original Message-----
From: ubuntu-users-bounces at lists.ubuntu.com [mailto:ubuntu-users-bounces at lists.ubuntu.com] On Behalf Of Smoot Carl-Mitchell
Sent: Tuesday, April 07, 2009 12:16 PM
To: Ubuntu user technical support, not for general discussions
Subject: Re: How to return user name in a script even if run by SUDO?

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

-- 
ubuntu-users mailing list
ubuntu-users at lists.ubuntu.com
Modify settings or unsubscribe at: https://lists.ubuntu.com/mailman/listinfo/ubuntu-users




More information about the ubuntu-users mailing list