0

So, let's say I have a shell script that's supposed to be run as root, but I want to execute commands using runuser as the user who is running sudo. I could do runuser -u tux echo penguin. However, what if I want to get the username of the user that ran sudo from within the root shell as root, to avoid hard-coding the username to run as into the script. How can I do this?

1
  • If you want to find who started some running application (using sudo), I would use a command line with ps: ps -ef |grep 'sudo ' and look at the user name in the first column.
    – sudodus
    Commented Apr 13, 2023 at 15:53

1 Answer 1

4

Use the SUDO_USER variable:

$ env | grep SUDO
$ sudo env | grep SUDO
SUDO_COMMAND=/sbin/env
SUDO_USER=terdon
SUDO_UID=1000
SUDO_GID=1000

So, you can just check if the $SUDO_USER variable is set or not:

if [ -n "$SUDO_USER" ]
then
   # run commands related to the original invoking user
fi
0

Not the answer you're looking for? Browse other questions tagged .