红联Linux门户
Linux帮助

设置Linux关机时自动运行指定命令

发布时间:2016-11-06 15:15:03来源:topspeedsnail.com作者:斗大的熊猫
我们一般设置Linux在开机时运行某条命令,关机时很少使用,本文就介绍一下怎么设置Linux在关机前自动运行某条命令。
要想在开机时运行某命令,我们只需把该命令写入到/etc/rc.local文件即可。如果要设置后台服务,参看:Python脚本开机自启动(Linux)(http://www.linuxdiyf.com/linux/25770.html)。
 
systemd
如果你的系统使用systemd,你可以在/lib/systemd/system-shutdown/目录中添加一个脚本,systemd-halt.service(https://www.freedesktop.org/software/systemd/man/systemd-halt.service.html)会处理这个目录中的脚本。
 
示例(Ubuntu 16.04):
$ sudo vim /lib/systemd/system-shutdown/cleanup.service
[Unit]
Description=Run command at shutdown
# 假设要执行的命令依赖网络
Requires=network.target
DefaultDependencies=no
Before=shutdown.target reboot.target
[Service]
Type=oneshot
RemainAfterExit=true
ExecStart=/bin/true
ExecStop=<要执行的命令>(/bin/touch /home/snail/hello) 
[Install]
WantedBy=multi-user.target

systemd官方文档:https://www.freedesktop.org/wiki/Software/systemd/
设置Linux关机时自动运行指定命令
 
参考:
http://askubuntu.com/questions/416299/execute-command-before-shutdown-reboot
http://ccm.net/faq/3348-execute-a-script-at-startup-and-shutdown-on-ubuntu
 
本文永久更新地址:http://www.linuxdiyf.com/linux/25771.html