This answer is intended to be a sort-of-compendium of some of the other answers here. If you're interested, I found this Q&A in this search.
The headline Question is:
Identify user in a Bash script called by sudo
AIU the Question posed by the OP, he wants to get at the name of the "logged-in-user" who started a script using sudo myscript.
Several of the answers here worked for me - on my system (Debian 'bookworm'), but judging from some of the comments, some that worked on my system did not work for others. I built a simple script that might be useful to others, so I'm adding it here:
#!/usr/bin/env bash
# my $0 is tstr.sh
echo -e "'whoami' ===> $(whoami)"
echo -e "'who am i' ===> $(who am i)"
echo -e "'echo \$SUDO_USER' ===> $SUDO_USER"
echo -e "'logname' ===> $(logname)"
You can run this as a regular user, under sudo tstr.sh, from sudo su -, from sudo -i, etc, etc:
$ sudo tstr.sh
'whoami' ===> root
'who am i' ===> seamus pts/2 2024-11-18 06:12 (192.168.1.209)
'echo $SUDO_USER' ===> seamus
'echo $(logname)' ===> seamus
$ sudo su -
root@sys3a:~# cd /home/seamus && ./tstr.sh
'whoami' ===> root
'who am i' ===> seamus pts/2 2024-11-18 06:16 (192.168.1.209)
'echo $SUDO_USER' ===>
'logname' ===> seamus
$ exit && sudo -i && cd /home/seamus && ./tstr.sh
'whoami' ===> root
'who am i' ===> seamus pts/2 2024-11-18 06:18 (192.168.1.209)
'echo $SUDO_USER' ===> seamus
'logname' ===> seamus
It seems that logname is the most consistent answer to the Question. who am i strikes me as a potentially troublesome answer b/c it winds up spawning another pts to get the correct answer. This may create other issues depending on the requirements of the script in use, and there's no system manual for it.