Shell – How to execute as the logged-in user in a sudo script (OSX)

commandexecnot-root-usershell-scriptsudo

Is there a way to switch contexts like that?

The script in my specific case is an installer postinstall script, which requires sudo privileges only for some of the tasks and requires the logged-in user to execute a LaunchAgent at the end of the script.

If this agent is started with sudo privileges, paths to logs and other resources that are user specific (placed in the user dir) get messed up.

Best Answer

This is what worked for me:

USER_NAME=$(printf '%s' "${SUDO_USER:-$USER}")

sudo -u $USER_NAME <command-to-exec-in-nonroot-context>
Related Question