Running a systemd user service before shutdown

Hi, I’ve been trying to run a script right before shutdown using systemd, but I can’t make it work. This is my service file:

#epush.service
[Unit]
Description= Pushing commits for emacs config at shutdown
DefaultDependencies=no
Before=shutdown.target

[Service]
Type=oneshot
ExecStart=/home/esbon1253/scripts/epush.sh 'commit before shutdown'
TimeoutStartSec=0
[Install]
WantedBy=shutdown.target

My bash script is basically a git push script for my emacs config, and I’ve tried many things: creating it as a system service, which didn’t work because of unsafe directory git error, as system services demand root. I could’ve chowned, but that would also mean rooting every time I wanted to execute a git command.
I followed a guide, (I can’t post the link), but the final product is exactly the same as my service file.
When I run:

systemctl --user enable --now epush.service 

It works fine, as I check with:

journalctl --user  -au epush.service --no-pager

But when actually running shutdown, the script never starts running. Do you think there’s a workaround, or maybe I should try to make it work as a system service?

How about this method:

…pretty much:
This file
~/.config/systemd/user/before-shutdown.service

[Unit]
Description=Do stuff before shutdown

[Service]
Type=oneshot
RemainAfterExit=true
ExecStop=/home/esbon1253/scripts/epush.sh 'commit before shutdown'

[Install]
WantedBy=multi-user.target

Then do the things:

systemctl daemon-reload && systemctl --user enable before-shutdown.service
4 Likes

It doesn’t work, and when I enable it, i get this message:

Created symlink /home/esbon1253/.config/systemd/user/multi-user.target.wants/epush.service → /home/esbon1253/.config/systemd/user/epush.service.
Unit /home/esbon1253/.config/systemd/user/epush.service is added as a dependency to a non-existent unit multi-user.target.

Maybe it has to do with it being an user service and not system, but I’m not sure…

Ah yes … makes sense multi-user.target is not user either.
I had of course adapted it from a non-user service.
default.target however should work.

[Unit]
Description=Pushing commits for emacs config at shutdown

[Service]
Type=oneshot
RemainAfterExit=true
StandardOutput=journal
ExecStop=/home/esbon1253/scripts/epush.sh 'commit before shutdown'

[Install]
WantedBy=default.target

Then do the same things:

systemctl daemon-reload && systemctl --user enable before-shutdown.service

(though note that this is technically before logout … please advise if this is undesirable)

3 Likes

It worked perfectly.

I don’t mind having it that way, so thanks!

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.