bashsudoupstart

changing user in upstart script


I have an upstart script that does some logging tasks. The script testjob.conf looks like below:

description "Start Logging"
start on runlevel [2345]

script
  sudo -u user_name echo Test Job ran at  `date` >> /home/user_name/Desktop/jobs.log
end script

Then I run the script with sudo service testjob start and I get testjob stop/waiting as result. The file jobs.log is created and the logging is done. However the file is owned by root. I wanted to change this and hence added sudo -u user_name part infront of the command mentioned in this similar post.

However this doesnot seem to do the trick. Is there another way to do this ?


Solution

  • The log file is created by the >> indirection which runs in the context of the root shell that also starts sudo.

    Try making the process that sudo starts create the file, for instance with:

    sudo -u user_name sh -c 'echo Test Job ran at  `date` >> /home/user_name/Desktop/jobs.log'
    

    In this case the sh running as user_name will "execute" the >> indirection.