7

I am really hoping to find some advice here. I am trying to setup a service in systemd that executes a .sh script at shutdown (and only at shutdown, halt and/or poweroff; NOT at reboot) of the the Pi. The service script is located in

/etc/systemd/system/

Setup: Raspberry Pi 2 with OSMC 2016.10-1 (linux kernel 4.4.27-2-osmc). So far, I stumbled around the web and found some snippets to setup the service as follows:

[Unit]
Description=executed at shutdown
Conflicts=reboot.target 
After=network.target

[Service]
Type=oneshot
ExecStart=/bin/true
ExecStop=/path/to/script
RemainAfterExit=yes

[Install]
WantedBy=multi-user.target

But I simply lack the necessary knowledge of systemd and how to execute a bash script within this service to get it properly running.

As starting point, I have created a simple script test_script.sh to check, if the service is running as expected and executes the script right before shutdown:

#!/bin/sh
echo 'the script is executed' > test.txt

it's located in the /home directory and executable after chmod 755

Using the command

bash test_script.sh

executes this script as expected and the file is created. But once the service is setup and enabled using systemctl, the script seems not to be executed before shutdown of the Pi.

What is going wrong here? Maybe there is someone who can point me in the right direction. I would really appreciate any help - many thanks in advance!

1

Based on this answer over on another site, you basically just create and enable a normal service, but write everything in reverse. Credits to linked answer.

[Unit]
Description=runs only upon shutdown
Conflicts=reboot.target
After=network.target

[Service]
Type=oneshot
ExecStart=/bin/true
ExecStop=[whatever you need to run]
RemainAfterExit=yes

[Install]
WantedBy=multi-user.target

Then run systemctl daemon-reload and systemctl enable myService.whatever --now.

0

After addressing the question here, I was able to solve the problem by spedifying a user in the [Service] section:

[Service]
User=osmc
ExecStart=/bin/true
ExecStop=/path/to/script
RemainAfterExit=yes

Now the script is executed on system shutdown. Unfortunately this applies to reboot as well. Maybe someone can point out what to change in the [Unit] or [Install] section to relate this service only to system shutdown (halt)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.