2

I want to log something before shutdown or poweroff.

uname -a
Linux xxx 4.9.0-4-amd64 #1 SMP Debian 4.9.51-1 (2017-09-28) x86_64 GNU/Linux

systemctl get-default
graphical.target
runlevel
N 5

To edit my script.

sudo vim   /etc/systemd/system/graphical.target.wants/log.service
[Unit]
Description=Run command at shutdown
Before=shutdown.target reboot.target

[Service]
Type=oneshot
RemainAfterExit=true
ExecStop=/bin/bash /home/log.sh

To enable it.

sudo systemctl  enable  log.service
Failed to enable unit: File log.service: No such file or directory

How to fix it? What is the matter with the following setting?

sudo cat   /etc/systemd/system/log.service
[Unit]
Description=Run command at shutdown
After=shutdown.target reboot.target

[Service]
Type=oneshot
RemainAfterExit=true
ExecStop=/bin/bash /home/log.sh


[Install]
WantedBy=graphical.target

Enable it with sudo systemctl enable log.service without any issue.
Why no log info ,the /home/log.sh can't execute?

showkey
  • 323

1 Answers1

3

You should not create units in the graphical.target.wants directory, that directory is meant for symlinks. Instead, create it directly in the /etc/systemd/system directory.

Furthermore, you want to have an [Install] section, describing where to install it when the systemctl enable command is used. (In your case, you could use graphical.target, though multi-user.target is a more common choice and it's a dependency of graphical.target, so it will be pulled during boot.)

So create this under /etc/systemd/system/log.service:

[Unit]
Description=...

[Service]
...
ExecStop=/bin/bash /home/log.sh

[Install]
WantedBy=multi-user.target

And then enable it with:

$ sudo systemctl enable log.service

This should work then.

It is possible that your dependencies are incorrect. You have Before=shutdown.target reboot.target, but most likely you need to use an After= dependency for services that you need to run before they are stopped. Dependencies work in an inverse order on shutdown, so list the ones you depend (such as local-fs.target, network.target) in that After= clause. The RequiresMountsFor= directive might also be interesting, for filesystems that you need mounted for your log.sh to be able to run...

filbranden
  • 21,751
  • 4
  • 63
  • 86