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>'"
init is the first process that starts in a Linux system after the machine boots and the kernel loads into memory. Among other things, it decides how a user process or a system service should load, in what order, and whether it should start automatically.
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
Alternatively, you can use the daemon
function defined in your /etc/init.d/functions
file:
daemon --user=<user> $DIR/program
If you look into its syntax you can do other things like defining PID file location, setting nice level, and whatnot. It's otherwise really useful for starting up services as daemons. Services started up with daemon
can easily be terminated by another functions function, killproc
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With