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? – Kusalananda Jun 10 '19 at 08:36sudo su
it asks for password input whereas-S
doesn't – PDStat Jun 10 '19 at 08:40-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. – terdon Jun 10 '19 at 08:45-S
– PDStat Jun 10 '19 at 08:59su
does not usesudoers
. – Kusalananda Jun 10 '19 at 09:00su
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. – terdon Jun 10 '19 at 09:03su
changes its behavior if given the--
"end of options" marker. See, for instance,su - myuser -c 'echo "$@"; echo "$0"; echo "$USER";' -- sh a --foo -X
, and observe that 1) it doesn't work without the--
, giving the error you mentioned; 2) the shell gets the arguments correctly, including$0
. I cannot explain it right now, though. – fra-san Jun 10 '19 at 13:25