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?


Putting this before the main functions are called did the trick for me:

    if [ "`whoami`" != "runasuser" ]; then
        sudo -u runasuser bash "$0" "$@"

This will call the current script in a sub shell as the user of your choice and pass all your input into it.


You can use the su command as follows to do this in bash script:

su -c "command" -s /bin/sh Username

Where the -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" 

The -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.

  • In my case, this would not work, as there are a lot of input variables to pass and functions to call. One of my requirements is that the script be self-contained and be able to change its user while still handling the user-given input and calling the functions it defines. The script was already pretty fleshed out when the user requirement changed, and I wanted a way to accomplish this without re-writing it to call sudo almost every line. – MrDrMcCoy May 29 '14 at 3:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.