为什么自动运行服务不能在关机时执行?

Why the autorun service can't execute at poweroff?

cat /lib/systemd/system/test_shutdown.service       
[Unit]        
Description=hello world        
Before=poweroff.target shutdown.target reboot.target   
[Service]        
Type=oneshot        
ExecStart=/bin/bash   /home/test_shutdown.sh         
[Install]        
WantedBy=poweroff.target  shutdown.target reboot.target      

cat  /home/test_shutdown.sh   
echo "haha" > /home/test_sys/shutdown.txt        

ls  -al  /home/test_shutdown.sh        
-rwxrwxrwx 1 root root 42 Mar 31 19:08 /home/test_shutdown.sh        

ls  -al  /home/test_sys        
drwxrwxrwx  2 root root 4096 Mar 31 19:12         
drwxr-xr-x 14 root root 4096 Mar 31 19:08 

systemctl  enable  test_shutdown.service    

重启后没有/home/test_sys/shutdown.txt,为什么我的服务无法执行?

我重写了 /lib/systemd/system/test_shutdown.service 如下。

[Unit]    
Description=hello world   
DefaultDependencies=no   
Before=reboot.target poweroff.target shutdown.target    
[Service]    
ExecStart=echo "haha" >  /home/test_sys/test.txt   
Type=oneshot   
[Install]     
WantedBy=reboot.target  poweroff.target shutdown.target    

systemctl status test_shutdown.service
test_shutdown.service - hello world
Loaded: error (Reason: Invalid argument)
Active: inactive (dead)
[Unit]
Description=hello world
DefaultDependencies=no
Before=shutdown.target reboot.target halt.target

[Service]
ExecStart=/bin/bash /home/test_shutdown.sh
Type=oneshot

journalctl |grep test_shutdown.service
4 月 1 日 15:05:54 hwy systemd[1]:配置文件 /lib/systemd/system/test_shutdown.service 被标记为可执行。请删除可执行权限位。继续进行。

chmod 644 /lib/systemd/system/test_shutdown.服务

在你的第二个服务文件中,它应该是

ExecStart=/bin/echo "haha" > /home/test_sys/test.txt

systemd 需要一个绝对路径。

您还没有提供第一个代码的 systemctl status。可能是写权限问题,也可能是您的 shell 解释器不是 /bin/bash。最好在 shell 脚本中使用 shebang #!/bin/sh