At your service

Ok, let’s take back a little bit of content of mine I previously donated to Stackoverflow. In this answer I was trying to setup a one-shot systemd service to trivially launch one of my fabulous scripts.

Well, none of the SO answers there or elsewere worked for me. But this post eventually did.

What did the trick was the RemainAfterExit=true directive. That’s because my script didn’t leave any trace of itself for systemd to look at, so next systemd step was always to call ExecStop to stop “this strange script that doesn’t leave a daemon behind”. Moot but true.

[Unit]
Description=Setup foo
#After=network.target

[Service]
Type=oneshot
ExecStart=/opt/foo/setup-foo.sh
RemainAfterExit=true
ExecStop=/opt/foo/teardown-foo.sh
StandardOutput=journal

[Install]
WantedBy=multi-user.target

UPDATE 20180316: Ok, I totally forgot everything about systemd services in these few months, so I was re-doing all the work from scratch. Fortunately I vaguely remembered about this answer, passed half an hour looking for it and now I’m here again.

I’ll try to add just a couple of things I’ve re-learned this time: systemd scripts must not be placed in /etc/init, they stay in the more hideous /etc/systemd/system directory, and they’re called .service, not .conf!

After the script is in the correct directory, a sudo systemctl daemon-reload is desirable, but won’t make the script name appear in sudo service [TAB] autocomplete list. Nevertheless, the new service can be launched with:

sudo service myservice start

And that’s it, now the service is doing what has been written for. For sure the called script won’t, but this is another problem.