I am currently making an upstart job run as an unprivileged user like so:

start on started mongodb
stop on runlevel [06]

respawn limit 10 100

env NODE_ENV=production

pre-start script
    ulimit -n 2048
end script

exec sudo -u mainuser /usr/bin/make -C /home/mainuser/app start-prod >> /home/mainuser/data/logs/app.log 2>> /home/mainuser/data/logs/app.err.log

This works good, with one exception: the log files app.log and app.err.log are being written as root (root becomes the owner of these files).

How do I ensure that the log files are written by the unprivileged mainuser?

1 Answer 1


Some thoughts from the top of my head: you could use | sudo -u mainuser tee to write the file (but if you want to split STDOUT and STDERR it can become a bit messy), or you could in the script check if the log files exist and are owned by mainuser, if not create and chown mainuser. Then appending output as you do would keep ownership.

Quick snippet:

for i in /home/mainuser/data/logs/app.log /home/mainuser/data/logs/app.err.log; do
    if [ ! -f "${i}" ] || [ "$(stat -c%U -- "${i}")" != "${user}" ]; then
        touch -- "${i}"
        chown ${user}:${group} -- "${i}"

This is quick and doesn't handle cases such as the log files existing as directories/links and so on very nicely, but in practice it might be fine.

I haven't worked with Upstart though, so maybe there are simpler ways.

  • I don't think an unprivileged user can "steal" or chown a file owned by root. The tee hint is more interesting, but before I try to implement it I will wait and see if there are any better options available, if you don't mind. Maybe I should just modify my make script so that it will do the logging.
    – Tom
    May 20, 2012 at 15:43
  • @Tom: You run the above test as root in the upstart script, in the pre-start script section I would guess, before dropping privilege to mainuser. Only root can chown as well. May 20, 2012 at 15:50

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.