Run script with arguments as user
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 can do everything you require. You also don't need
$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 "$@"
There are two problems with your script:
1) You forgot the spaces in the test command
[`whoami` = myuser]
2) Due to the expansion of the variable "$@" in two steps the quoting is lost.
The following seems to work on my system:
[ `whoami` = myuser ] || exec sudo -S -u myuser bash -- "$0" "$@"
If the whole script would need to be run by a specific user, then I would leave it up to the user running the script to arrange with changing into the correct user identity in any way that they see fit (whether through
sudo, or some other means).
This would simplify your script and would make it easier to use. In particular, it would avoid having to "correct" for the inability of the user to assume the right identity. Personally, I would treat this as an error in its invocation, similar to failing to use the correct command line options.
The script could still check to make sure that it's being run by the correct user, obviously:
if [ "$USER" != "correctuser" ]; then echo 'Must be run by "correctuser"' >&2 exit 1 fi
An ordinary user would then run the script using
sudo -u correctuser ./script.sh -e dev -v 1.9
while the root user may want to do
su correctuser -c ./script.sh -e dev -v 1.9