How to let 'systemd' runs a script when service-name.service stops?

Hi!

I can't get it work

I added to a self created 'systemd' script:

ExecStop=/path-to/stop.sh

The 'stop.sh" script is supposed to execute bash commands when my self created systemd service is stopped.

Unfortunately it does not work.

My 'stop.sh" script is not executed.

What am I doing wrong?

There's a whole boatload of things that could be going wrong.

For one thing, you need to ensure your stop script is executable:

sudo chmod 755 /path-to/stop.sh

Does the path to your script contain any spaces or other funky characters? If so, eliminate them.

Is the name in the .service file consistent with the name and path of the script itself?

When you run:

/path-to/stop.sh

...does the script do what it's supposed to do? Are there any syntax errors? Does the script return any non-zero return values?

if [ $? -eq 0 ]; then
  echo "Everything is cool, bro."
else
  echo "Time to panic...  The script returned a nonzero value.  SystemD will not necessarily like that."
fi

Finally, can you start and stop your service, and then look at the last few lines of the system log?

sudo service my-systemd-service start
sudo service my-systemd-service stop
sudo journalctl | tail -50

Maybe the last few lines of the system log will shed some light on the issue.

Good luck, and I hope to hear back from you soon.

2 Likes

I'll try it out in the next days. Thanks!
Best regards!