I have an init script to kick off a daemon. The problem is it runs as root. I would like it to run as a user called "deploy". Ubuntu 12.04

#! /bin/sh

# File: /etc/init.d/unicorn

# Provides:          unicorn
# Required-Start:    $local_fs $remote_fs $network $syslog
# Required-Stop:     $local_fs $remote_fs $network $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: starts the unicorn web server
# Description:       starts unicorn

DAEMON_OPTS="-c /var/www/current/config/unicorn.rb -D"

case "$1" in
    echo -n "Starting $DESC: "
    echo "$NAME."
    echo "Usage: $NAME {start|stop|restart|reload}" >&2
    exit 1

exit 0
  • 2
    Change $DAEMON $DAEMON_OPTS to su - deploy -c "$DAEMON $DAEMON_OPTS" – daisy Dec 1 '12 at 9:56
  • Beware not to launch the deamon using the "service" command while you are testing since the chuid option will have no effect and the process will run as root. – pasqal Sep 15 '15 at 14:49
  • Are all scripts in init.d called after kernel already knows the users in system ? – ransh Mar 19 '17 at 10:06

Use the start-stop-daemon utility to start your daemon. Pass the -c (or --chuid) option to run it as a different user. You'll find some examples in /etc/init.d/*.

case $1 in
    echo -n "Starting $DESC: "
    start-stop-daemon --start --chuid deploy --pidfile "$PID" --start --exec "$DAEMON" -- $DAEMON_OPTS
    echo "$NAME."
  • Are all init.d scripts called after kernel already knows all users in system ? – ransh Mar 19 '17 at 10:07
  • @ransh I'm not sure what you're asking. The kernel does not really “know” users: as far as it's concerned, a user is just a number, and it doesn't care what the number is except that processes running as user 0 can do many things that other users can't. – Gilles Mar 19 '17 at 21:52

On Ubuntu you can use just

sudo -u deploy $DAEMON $DAEMON_OPTS

  • Why add sudo when su or --chuid exists? What if sudo is not installed? – Jeff Schaller May 8 '16 at 15:05
  • 1
    @JeffSchaller sudo is installed on Ubuntu – Роман Коптев May 8 '16 at 21:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.