关机时 Systemd 脚本未运行

关机时 Systemd 脚本未运行

我一直在努力解决这个问题但没有成功,我也不知道为什么我的脚本在关机时不能运行......

运行 Ubuntu 20.04(桌面版)。

我创建了一个 /usr/local/sbin/run_on_shutdown.sh:

#!/bin/sh
REBOOT=$( systemctl list-jobs | egrep -q 'reboot.target.*start' && echo "rebooting" || echo "not_rebooting" )
if [ $REBOOT = "not_rebooting" ]; then
########################################################################
# Put Bash commands here to be executed on shutdown but not on reboot. #
# For example, backup home directories to an external USB HDD. #
########################################################################

curl --silent --show-error -X POST https://example.com/trigger_something/abcdefkey
fi

我有chmod +x /usr/local/sbin/run_on_shutdown.sh

并创建一个 systemd 服务:

[Unit]
Description=Run run_on_shutdown.sh at shutdown
DefaultDependencies=no
Requires=network.target network-online.target
Before=network-online.target shutdown.target halt.target

# If your script requires any mounted directories, add them below:
# RequiresMountsFor=/home

[Service]
Type=oneshot
ExecStart=/usr/local/sbin/run_on_shutdown.sh

[Install]
WantedBy=multi-user.target halt.target shutdown.target

设置权限chmod 644 /etc/systemd/system/run_on_shutdown.service

重新加载守护进程:sudo systemctl daemon-reload

并启用它:sudo systemctl enable run_on_shutdown.service

但是...它不会在关机时运行...而是运行sudo systemctl enable run_on_shutdown.service --now

我找不到任何证据表明它在关机时被调用,所以......

有人可以帮助我或者给我指明正确的方向吗?

谢谢!

答案1

这将在 /opt/tmp 上创建文件 shutdown.log,shutdown.target但不会在reboot.target

[Unit]
Description=My Shutdown Service
DefaultDependencies=no
Before=shutdown.target reboot.target
Conflicts=reboot.target

[Service]
ExecStart=/bin/bash \
    -c 'mkdir -p /opt/tmp && \
        echo shutdown | ts >> $_/shutdown.log'
Type=oneshot
RemainAfterExit=yes

[Install]
WantedBy=shutdown.target

相关内容