Who is the user behind `sudo` and how to get the group(itself) which a file belongs?

Hi !

I have a script which is the main entry of my program, I would like to know who is the user behind the sudo command when the command in question precedes my main script.

Here the concerned section (I tried the below scenario, but that not works) :


#!/bin/bash 

set -uo pipefail 


if [[ $1 == "sudo" ]] 
then
    echo "Okay $EUID    ....."
fi

Thanks for your help.

@ogra, @baldeuniversel you seem to know about shell (bash, zsh …), please help.

$SUDO_USER

sudo snap run --shell null
[sudo] password for alan:
root@ziggy:/home/alan# echo $SUDO_USER
alan
root@ziggy:/home/alan# exit

Thank you for answering. I got an error .

#!/bin/bash 

set -uo pipefail 

#
if [[ -n "$SUDO_USER" ]]
then
    #
    echo "$SUDO_USER"
fi

Output :

./main.sh: line 6: SUDO_USER: unbound variable

That’s because you’ve asked Bash to check with the set command, you’d either stop asking Bash to warn about those errors or set a fallback for when the variable isn’t set.

echo ${SUDO_USER:-}

Which will force the variable to exist but be empty if it doesn’t already have content.

2 Likes

Hi ! @entity .

You can apply the @James-Carroll suggestion, or ignore the -u option in the set -uo pipefail command.

By the way, the fact that the -u option is activated and that the environmental variable $SUDO_USER appears in your code, without preceding the execution of your program with sudo it will inevitably crash (without some measurements), because the existence of the environmental variable $SUDO_USER is intrinsic to the sudo command.

As for how to find the group (the group itself) to which a file belongs, you can use the Linux command stat.

1 Like

Thanks you all very much :slightly_smiling_face:, it’s very clear now @baldeuniversel @James-Carroll @popey.

1 Like