仅在关机时在 systemd 服务上运行脚本而不是重新启动

5 linux shutdown systemd

[Unit]  
Description=test  
Before=shutdown.target

[Service]  
ExecStart=/bin/true  
ExecStop=/usr/local/bin/test.sh  
RemainAfterExit=yes

[Install]  
WantedBy=multi-user.target
Run Code Online (Sandbox Code Playgroud)

我尝试了很多例子,但没有奏效。上面的例子适用于重启和关机。我只想在关机时工作。

我没有服务器。这是我的个人电脑。我有 Gnu/linux 操作系统。是否可以仅在关机时运行脚本而不重新启动?

ing*_*oxd 1

您可以在脚本中测试是否要重新启动、停止或关闭系统电源,并决定相应的操作。

例如:

#!/bin/bash
if ! systemctl list-jobs | grep -q -e "reboot.target.*start"; then
   printf "Not rebooting\n"
fi
Run Code Online (Sandbox Code Playgroud)

您可以在其中man systemd.special看到所有目标。您可能需要更多关注:

  • 关闭目标
  • 重新启动.目标
  • 暂停目标
  • 断电目标