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.
[
and]
must have spaces after and before them, respectively. Why do you needsudo su
? Is notsudo
enough? Do you really need to start an interactive or login shell? And if the user hassudo
access, why use-S
(used for passing a password over standard input)? Related: Is there ever a good reason to run sudo su?sudo su
it asks for password input whereas-S
doesn't-S
, that just allows you to do something likeecho password | sudo -S command
. If it didn't ask for a password, that's because you've recently run anothersudo
command so it still remembers the password. Runsudo -k
to forget it and try again and it will ask for a password.-S
su
to be run withsudo su
without needing a password throughsudoers
. That said, I have absolutely no idea how or why the-S
flag could possibly be relevant.