Linux下实现关机或重启前执行脚本

本文是以使用 systemctl 的方式来自定义关机前执行脚本。

1.创建 systemd 服务

vim /usr/lib/systemd/system/shutdown-clean.service

创建该文件并写入如下内容,需要把 ExecStart=/some/scripts/com/monitor.sh 这一行换成自己的脚本路径

[Unit]
Description=close services before reboot and shutdown
DefaultDependencies=no
Before=shutdown.target reboot.target halt.target
#Before=network.target iscsi.service iscsid.service shutdown.target reboot.target halt.target
# This works because it is installed in the target and will be executed before the 
# target state is entered
# Also consider kexec.target

[Service]
Type=oneshot
ExecStart=/some/scripts/com/monitor.sh

[Install]
WantedBy=halt.target reboot.target shutdown.target

2.启动服务

systemctl enable shutdown-clean.service

关机和重启前,就会自动执行你自定义的脚本

猜你喜欢

转载自blog.csdn.net/xiao3404/article/details/131178451