Graceful exit bash script when running as a service with systemctl

Viewed 331

I've set up a service in /etc/systemd/system/ called my_script.service. After that I run:

sudo systemctl daemon-reload
sudo systemctl start my_script.service
sudo systemctl stop my_script.service

I would like the script to "die" gracefully.

When I run the script from the CLI, I have a trap ctrl_c INT function that runs when I hit ctrl+c to stop the script.

How can I get the same functionality using systemctl?

2 Answers

Trap TERM as well as INT. TERM is the non-interactive analogue to INT; interactively pressing Ctrl-C triggers INT, whereas non-interactive process killing is usually done with TERM.

Turns out all I had to do is change

trap ctrl_c INT

to

trap ctrl_c SIGTERM

Related