45

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.

Jörg Haubrichs
  • 2,215
  • 3
  • 24
  • 26

4 Answers4

44

On my system the variable $SUDO_USER is set to the caller's user name.

You shouldn't extract the username from the ${HOME} variable directly. It's being configured and not calculated. To Extract the username you could take a look into /etc/passwd file, but this is very system dependent, e.g. sometimes you have to look into a LDAP directory or the entries are propagated through NIS ...

user
  • 5,335
  • 7
  • 47
  • 63
dz.
  • 1,286
  • 12
  • 12
  • 4
    For those landing here because gnome-terminal dropped support for `logname`, this seems to work well `$(logname 2>/dev/null || echo $SUDO_USER)`. Tested on MacOS too. Bug report: https://bugzilla.gnome.org/show_bug.cgi?id=747046 – tresf Nov 14 '16 at 19:35
  • logname 2>/dev/null || echo $SUDO_USER , command worked for me in the OS Ubuntu 16.04.6 LTS and Ubuntu 20.04 LTS. – Syed Faraz Umar Jun 05 '20 at 09:42
28

You can use $(logname), which returns your login name even if you are currently sudoing.

Gauthier
  • 40,309
  • 11
  • 63
  • 97
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;}'
brianegge
  • 29,240
  • 13
  • 74
  • 99
9

SUDO_USER isn't portable. It's unset on Fedora 17.

The $USER and $UID variables aren't predictable when invoking sudo either. Some distros report the sudoer, others report the root user.

It's by no means perfect, but you could use test -w ~root && echo I have write access to ~root.

Jim S.
  • 91
  • 1
  • 1