Alex Rivera | Logout

Getting $USER inside shell script when running with sudo?

Asked 2009-10-27T09:19:01.973
47

How do I get the correct $USER if I run a shell script with sudo ?

I run them as postinstall scripts in a Mac install package, where they are being sudo-ed automatically, but I need to do stuff with the username.

$HOME is correct, though. The inelegant method would be to extract the name from the home path, but I wonder if there is a natural way to do this.

I can't influence the way the scripts are being called, as it's an automatic call inside the installer.

Edit
Report

1 Answer

19

Inspect the variable SUDO_USER.

http://www.gratisoft.us/sudo/man/sudo.html#environment

Another way to get the user is via the who command. This is useful sometimes when you don't care if the user has sudo'd or not.

who -m | awk '{print $1;}'
answered 2009-10-27T09:27:18.363

Your Answer