Having the same question, using Rocky Linux 9.2, I ran this script:
#!/bin/bash
echo "LOGNAME: $LOGNAME"
echo "SUDO_USER: $SUDO_USER"
set | grep username
in each of these scenarios:
as user (./script.sh
)
- LOGNAME: username
- SUDO_USER: null
as root via sudo (sudo ./script.sh
)
- LOGNAME: root
- SUDO_USER: username
as root via su (./script.sh
)
- LOGNAME: username
- SUDO_USER: null
as root via sudo su (./script.sh
)
- LOGNAME: root
- SUDO_USER: username
Using an if...then...else check would work, unless you inadvertently sudo
run the script while you are already at the superuser
prompt:
#root: sudo ./script.sh
- via either su or sudo su the results are
- LOGNAME: root
- SUDO_USER: root
However, one set
variable has proven to be consistent though all of my scenarios:
MAIL=/var/spool/mail/username
I now set the logged in user as:
UNAME=$(echo $MAIL |cut -d/ -f5)
I'm sure there are situations where this would not work, but I haven't found one yet.
who am i
iswho mom likes
. Your choice. – Parsee