Is there a "reverse sudo"?

Both su and sudo can do this. They run a command as another user; by default that "another user" is root, but it can be any user. For example,

sudo -u www-data ls

will run ls as the user www-data.


However...

The usual way is to run the script as the invoking user and use sudo for those commands which need it. sudo caches the credentials, so it should prompt at most once.


sudo exports environment variables SUDO_COMMAND, SUDO_GID, SUDO_UID, and SUDO_USER.

You can use SUDO_USER or SUDO_UID to get back to the invoking user:

sudo -u "$SUDO_USER" an_unprivileged_command

sudo is a souped-up version of su with better access controls. If you're already running as root, su will do it with no fuss:

#!/bin/sh -e
echo -n "Script User:          " && id -un
echo -n "Other user:           " && su blrfl -c "id -un"
echo -n "Back to script user:  " && id -un

When run, you get this:

Script User:          root
Other user:           blrfl
Back to script user:  root

Tags:

Shell Script