Monday, May 20, 2024
13
rated 0 times [  13] [ 0]  / answers: 1 / hits: 5407  / 3 Years ago, sun, september 12, 2021, 11:54:56

What I want is to find the name of the user that runs bash script, when this script is executed by sudo. The only possible way, that I know, is to parse the output of who -m (who am i) in this way:





user@UbuntuServer:~$ cat who.sh 
#!/bin/sh
whoami
echo $USER
who -m | awk '{print $1}'

user@UbuntuServer:~$ sudo ./who.sh
root
root
user


The problem is: In Ubuntu Desktop 16.04.4 who -m (resp. who am i) do nothing. Why?



enter image description here



Another question is why the Ubuntu's online manual page for who is different from man who executed either on Ubuntu Desktop or Server?



But these questions are not so important according to my goals. And as it is mentioned in the title, the main question is: How do I find which user executes the script when is used sudo?






Practically, the original title - How do I find 'who am I' on Ubuntu Desktop? - is the same but wrongly asked question.


More From » command-line

 Answers
4

I had a similar problem a while ago, and the only way that has worked reliably for me so far, is:



echo ${SUDO_USER:-${USER}}


As long as the user works with the shell as himself, $USER contains his username. When he calls sudo, for the new subshell $SUDO_USER is set to what is $USER in the calling shell, and $USER becomes root, of course.



The trick with the operator :- is, that the whole expression evaluates to $SUDO_USER if it is set (so inside the subshell opened by sudo), and otherwise to $USER. Therefore, you always have the correct username and don't have to worry much about the context the expression is evaluated in, which I found to be convenient.


[#8308] Monday, September 13, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
brellked

Total Points: 63
Total Questions: 107
Total Answers: 104

Location: Morocco
Member since Fri, May 22, 2020
4 Years ago
;