0

I have a bash shell script that must be run as root. If a user launches it they are asked for the root password and the script is rerun in a subshell. ./$0 &

Let's say a user named 'John' launches the script. After he provides the root password the script is rerun as root, but how can i tell who originally launched the script (John) from within the script itself? At the moment I am dumping a file with the original launcher which I can reference later but this is ugly.

Other options I considered are using the process list but again, there must be a more elgant solution.

GNU bash, version 4.2.45(2)-release (x86_64-slackware-linux-gnu)

user316100
  • 271
  • 1
  • 3
  • 5

3 Answers3

6

You can use the $SUDO_USER variable.

#!/bin/bash

echo $SUDO_USER

output

[use1r@host]$ ./sudo-print.sh

[user1@host]$ sudo ./sudo-print.sh
user1
arco444
  • 22,002
  • 12
  • 63
  • 67
0

Try using SUID to set the permissions the file uses to execute with. This might keep your UID during execution if you are lucky, then you can scrape your UID a lot easier.

user2691041
  • 145
  • 1
-1

Check the Parent process id of the script ... owner of the parent process should be the user who executed the file.

To get the ppid probably you can use

echo $$

Or you can try to includle the code below in yoru bash script to return the original user

who am i
  • 1
    `$$` is the process ID of the current shell, which is not the owner of the script. You would need the process ID of the `sudo` command that runs the script. – chepner Mar 02 '14 at 16:24
  • As far as i remember for a subshell echo $$ would return process id of the parent shell... .. i don't have access to a linux terminal to verify this at this moment.. OR you can do a echo $PPID to get the parent process id – Nishant Shrivastava Mar 02 '14 at 16:32
  • I just tried on an online terminal #!/bin/bash ; echo $$; ( echo $$) .. both returned the same value – Nishant Shrivastava Mar 02 '14 at 16:34
  • `$$` always has the value of the parent shell in a subshell. However, `sudo` is not a subshell; it's a wholly separate process that runs the requested command in still another process. – chepner Mar 02 '14 at 16:35
  • The question says : I have a bash shell script that must be run as root. If a user launches it they are asked for the root password and the script is rerun in a subshell. ./$0 & -- So if the script has echo $$, would it not return the process id of the shell where the command was entered? I get a shell when I log in .. and the owner of that shell process would be me.. in the case of this question.. this user happens to be 'John'. – Nishant Shrivastava Mar 02 '14 at 16:40
  • All 3 gave the same output #!/bin/bash echo $$ ( echo $$) echo $$PPID – Nishant Shrivastava Mar 02 '14 at 16:42