MacOS – How to determine the invoking user in an Apple installer postinstall script

installmacos

I want to build an apple installer .pkg where I run a postinstall script after the files have been copied by the installer. The script is run and everything works perfect except that all the commands in the script are run as root.

The question is, how can I determine the id of the user who actually invoked the installer.

who -m

returns the invoking user when I run the script on the command line with sudo. But it returns root when I run it in the installer.

Is there any way to get the "actual user"?

Thanks for your help!

Best Answer

After some testing, I believe I have found that one of the best options for this is

INSTALLER_USER=$(stat -f '%Su' $HOME)

I have found that the $HOME environmental variable of the user installing the package is passed through, even after elevating for Installer.app or using the installer command.

The previous answers are assuming some things about the environment that may not always be true.

For example CONSOLE_USER=$(ps aux | grep console | grep -v grep | cut -d' ' -f1) does not work in there are multiple users logged in, as may be the case in a computer lab environment.

As for ps aux | grep "CoreServices/Installer" | grep -v grep | awk '{print $1;}'; this only works if the user is actually running Installer.app and would not apply to someone running it with the installer command in a shell.