I am trying to create an init script in bash (Ubuntu) that starts a service under a specific user.
Is there a better way to do that other than this?
su - <user> -c "bash -c 'cd $DIR ;<service name>'"
Ubuntu uses start-stop-daemon
which already supports this feature.
Use the skeleton file from /etc/init.d:
sudo cp /etc/init.d/skeleton /etc/init.d/mynewservice
Edit mynewservice appropriately.
Add the following parameter to the lines that call start-stop-daemon:
--chuid username:group
Example:
Change
start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON --test > /dev/null \
to
start-stop-daemon --start --quiet --chuid someuser:somegroup --pidfile $PIDFILE --exec $DAEMON --test > /dev/null \
Finally, register your service and start it:
update-rc.d mynewservice defaults 99 && service mynewservice start
More info about other options for start-stop-daemon here