Systemd service script fails to write into a file
I want user based service. So I created [email protected]
in /etc/systemd/system
with following content.
[Unit]
Description=My Service
[Service]
Type=simple
ExecStart=/bin/bash ${HOME}/userscript
WorkingDirectory=${HOME}
Restart=always
RestartSec=2
User=%i
[Install]
WantedBy=multi-user.target
Following is content of ${HOME}/userscript
#!/bin/bash
while true;
do
echo $(date +%Y%m%d%a%H%M%S) >> log
echo $USER >> log
sleep 2
done
Then I enable and start the service using:
systemctl enable myservice@john
systemctl start myservice@john
This is what I get when I check service status:
● [email protected] - myservice
Loaded: loaded (/etc/systemd/system/[email protected]; enabled; vendor preset: enabled)
Active: active (running) since Mon 2017-12-11 08:03:54 PST; 6s ago
Main PID: 11558 (bash)
CGroup: /system.slice/system-myservice.slice/[email protected]
├─11558 /bin/bash /home/john/userscript
└─11603 sleep 2
Dec 11 08:03:54 my-system-hostname systemd[1]: Started myservice.
Dec 11 08:03:54 my-system-hostname bash[11558]: /home/john/userscript: line 4: log: Permission denied
Dec 11 08:03:54 my-system-hostname bash[11558]: /home/john/userscript: line 5: log: Permission denied
Dec 11 08:03:56 my-system-hostname bash[11558]: /home/john/userscript: line 4: log: Permission denied
Dec 11 08:03:56 my-system-hostname bash[11558]: /home/john/userscript: line 5: log: Permission denied
Dec 11 08:03:58 my-system-hostname bash[11558]: /home/john/userscript: line 4: log: Permission denied
Dec 11 08:03:58 my-system-hostname bash[11558]: /home/john/userscript: line 5: log: Permission denied
Dec 11 08:04:00 my-system-hostname bash[11558]: /home/john/userscript: line 4: log: Permission denied
Dec 11 08:04:00 my-system-hostname bash[11558]: /home/john/userscript: line 5: log: Permission denied
The service should be writing datetime and user name after every 2 seconds, but this won't happen and instead I get permissions error. I have confirmed that service is being run as john
and I could get it echo
ed correctly. Permission issue appears when I try to write in the file.
Any clue?
UPDATE 1
Following is output of namei -lx /home/john/log
$ namei -lx /home/john/log
f: /home/john/log
Drwxr-xr-x root root /
drwxr-xr-x root root home
drwxr-xr-x john john john
-rw-rw-r-- john john log
I finally solved it. I had to add WorkingDirectory
directive, with value ~
. It now works without any permissions issue.
Thanks to @muru