I have a need to have a single script run the majority of its commands as another user, but do not want to instruct my users to call it via sudo. Running the commands with an EOF here document is not workable, as there are a lot of variables to pass from the input into various functions the script defines. Is there another way for me to run the functions as another user, while preserving the input and variables? Can this be done without calling a bunch of external files or adding sudo to nearly 300 commands?
You can use the
su command as follows to do this in bash script:
su -c "command" -s /bin/sh Username
-c parameter specifies spend a single command to the shell and
-s is used to specify which shell to call the command.
Another way to do this is through the use of sudo as follows:
sudo -H -u Username bash -c "command"
-h parameter is a security policy that allows you to set the environment variable HOME to the specified user (root is by default).
-u specifies the user to run the command.