Identify user in a Bash script called by sudo

LinuxBashSudo

Linux Problem Overview


If I create the script /root/bin/whoami.sh containing:

#!/bin/bash
whoami

and this script is called by a user with a properly configured sudo, it will indicate

root

Is there a fast way to obtain the actual user in a script, or will I have to resort to parameters passing along this username?

Linux Solutions


Solution 1 - Linux

$SUDO_USER doesn't work if you are using sudo su -.
It also requires multiple checks - if $USER == 'root' then get $SUDO_USER.

Instead of the command whoami use who am i. This runs the who command filtered for the current session. It gives you more info than you need. So, do this to get just the user:

who am i | awk '{print $1}'

Alternatively (and simpler) you can use logname. It does the same thing as the above statement.

This gives you the username that logged in to the session.

These work regardless of sudo or sudo su [whatever]. It also works regardless of how many times su and sudo are called.

Solution 2 - Linux

I think $SUDO_USER is valid.

#!/bin/bash
echo $SUDO_USER
whoami

Solution 3 - Linux

Here is how to get the username of the person who called the script no matter if sudo or not:

if [ $SUDO_USER ]; then user=$SUDO_USER; else user=`whoami`; fi

or a shorter version

[ $SUDO_USER ] && user=$SUDO_USER || user=`whoami`

Solution 4 - Linux

Using whoami, who am i, who, id or $SUDO_USER isn't right here.

Actually, who is never a solution to the question, as it will only list the logged in users, which might be dozens...

In my eyes, the only valuable answer is the use of logname.

Hope this helps

Rob

Solution 5 - Linux

If it's the UID you're looking for (useful for docker shenanigans), then this works:

LOCAL_USER_ID=$(id -u $(logname))

Solution 6 - Linux

who am i | awk '{print $1}' didn't work for me but who|awk '{print $1}' will serve the job

Solution 7 - Linux

Odd, the system does distinguish between real and effective UIDs, but I can find no program that exports this at shell level.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionquadmoreView Question on Stackoverflow
Solution 1 - LinuxevanView Answer on Stackoverflow
Solution 2 - LinuxBrandon HorsleyView Answer on Stackoverflow
Solution 3 - LinuxAlexei TenitskiView Answer on Stackoverflow
Solution 4 - LinuxRobView Answer on Stackoverflow
Solution 5 - LinuxJim HunzikerView Answer on Stackoverflow
Solution 6 - LinuxSrinivasView Answer on Stackoverflow
Solution 7 - LinuxmswView Answer on Stackoverflow