How to get the name of the user who executed a bash script as sudo?
Solution 1
I'm not sure how standard it is, but at least in Ubuntu systems sudo
sets the following environment variables (among others - see the ENVIRONMENT
section of the sudo manpage):
SUDO_UID Set to the user ID of the user who invoked sudo
SUDO_USER Set to the login of the user who invoked sudo
for example,
steeldriver@lap-t61p:~$ sudo sh -c 'whoami'
root
steeldriver@lap-t61p:~$ sudo sh -c 'echo $SUDO_USER'
steeldriver
Solution 2
If you want it to work without sudo
as well, use ${SUDO_USER:-$USER}
. For example:
printf '%s\n' "${SUDO_USER:-$USER}"
Explanation
${var:-val}
will expand to $var
, unless it's unset or empty, in which case it will expand to val
.
Related videos on Youtube
marcio
Contributor of many open source projects. Languages I work with: PHP Go Python Lisp Rebol and Red C (learning) C++ (learning)
Updated on September 18, 2022Comments
-
marcio over 1 year
I want to create a bash script that must be executed with sudo but should take into account the name of the non-sudo user who executed it. So if user
bob
runssudo ./myscript.sh
I would likemyscript.sh
to knowbob
was the one who executed it.Let's look inside
myscript.sh
:USER=$(whoami) # Do something that takes into account the username.
How can I know the name of the user who spawned the process? More specifically, what should I use instead of
whoami
to getbob
and notroot
? -
marcio almost 10 yearsWorks as expected on all platforms I tested: debian, fedora(redhat) and freebsd. Thanks!
-
SiKing almost 8 yearsConfirmed working on a Mac.