如何在 Ubuntu 21.04 上关机前运行命令

Sme*_*ink 5 reboot shutdown restart 21.04

我只想在 Ubuntu 21.04 上每次重新启动/关机/关机之前(当我运行关机或关机命令,或使用 GNOME/KDE GUI 选项时)运行(以 root 身份)命令或脚本。我尝试将脚本放入其中/etc/init.d并创建符号链接/etc/rc6.d//etc/rc0.d/但不起作用。

想知道是否有这样的线路sudo crontab -e

mat*_*igo 11

您可以通过创建服务文件,然后重新加载systemd. 就是这样:

  1. 打开终端(如果尚未打开)

  2. 确保要在关机时运行的脚本可执行:

    chmod +x ~/scripts/pre-shutdown.sh
    
    Run Code Online (Sandbox Code Playgroud)
  3. /etc/systemd/system为关闭服务创建一个文件。为了这个例子,我将我的文件称为nighty-night.service.

  4. 将以下行添加到.service文件中,并根据需要进行修改:

    [Unit]
    Description=Pre-Shutdown Processes
    DefaultDependencies=no
    Before=shutdown.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=/home/smeterlink/scripts/pre-shutdown.sh  # your path and filename
    
    [Install]
    WantedBy=halt.target reboot.target shutdown.target
    
    Run Code Online (Sandbox Code Playgroud)
  5. 重新加载 systemd,启用该服务,使其在引导时启动,然后启动它:

    sudo systemctl daemon-reload
    sudo systemctl enable nighty-night.service
    sudo systemctl start nighty-night.service
    
    Run Code Online (Sandbox Code Playgroud)

您可以查看它是否运行正常systemctl status nighty-night

这里的所有都是它的。

  • 步骤5:启用服务:`sudo systemctl enable nighty-night`。 (2认同)