7

I want to run a script when a user shuts their computer down, but it needs networking. So I'd like it to run when the system is heading for shutdown (or restart), but it needs to run before anything is unmounted or networking is shut off.

How can I do this?

artfulrobot
  • 2,929

1 Answers1

6

This question is very similiar to How to run a script with systemd right before shutdown?. With the twist that you want to be sure networking is up.

To cover that, add this to your service file:

After=networking.service

As the docs say, After= not only declares that your service is started by the networking service, it also is declaring that the services should be stopped in the inverse order-- before networking is shut down.

  • Is this any different than After=network.target? – rich remer Mar 22 '19 at 19:54
  • @richremer Compare for yourself the contents of network.target and networking.service on your system. You'll see they are different. Here I think using a .service is more appropriate, because a target is a like a "goal state" to boot up to. "Stopping a goal state" doesn't make as much sense as "stopping a service". In fact, either may work, but I think using a service is clearer here. – Mark Stosberg Mar 25 '19 at 14:16
  • 1
    Firstly, networking.service did not work for me. Secondly, https://www.freedesktop.org/wiki/Software/systemd/NetworkTarget/ says that you should use After=network-online.target + Wants=network-online.target. Can you edit your answer, @MarkStosberg ? – Greg Dubicki May 22 '19 at 18:09
  • network.service did not work for me neither – travisjayday Jan 25 '21 at 23:03