Run Script with Arguments as User Using Sudo or SU

susudousers

I am trying to make sure when a script is run it is run as a specific user without having to su to that user before the script is run. Also the script is run with a couple of flags for example

./myscript.sh -e dev -v 1.9

I have tried the following

[ `whoami` = myuser ] || exec sudo -S su - myuser -c "bash `pwd`/`basename $0` $@"

But the -v flag which is supposed to be an input to my script is being fed as input to su. So it complains of an invalid option, is there a way to correct the above?

NB: The person running the script has sudo privileges.

Best Answer

The current user is already in the variable $USER. So all you need is:

[ "$USER" = "myuser" ] || sudo -u myuser $0 "$@"

There is no need for sudo su, sudo can do everything you require. You also don't need pwd or basename, the $0 variable already has the full path to the script.

Your original command was starting a login shell (su -). If that's really needed (which seems strange), you can do:

[ "$USER" = "myuser" ] || sudo -iu myuser $0 "$@"
Related Question