Systemd – run a script before system shutdown

Here systemd will execute /srv/app_shutdown_script.sh before the system reboots. Refer to the following steps.

  1. Create a systemd Unit file with the following content.
# cat /etc/systemd/system/exec-before-shutdown.service
[Unit]
Description=Shutdown run script 
DefaultDependencies=no
Before=shutdown.target

[Service]
Type=oneshot
ExecStart=/srv/app_shutdown_script.sh
TimeoutStartSec=0

[Install]
WantedBy=shutdown.target

  1. Here we instructed the Unit file to run the script /srv/app_shutdown_script.sh before shutdown.target.
$ cat /srv/app_shutdown_script.sh

#!/bin/bash
c=0
for i in {1..3}; do
    sleep 1m
    ((c++))
    echo ""
done

  1. Reload the systemd configuration files.
       # systemctl daemon-reload

  1. Enable the Unit to automatically start at next boot.
    # systemctl enable exec-before-shutdown.service

Now reboot the system and confirm.

You May Also Like

avatar

About the Author: TekFik

TekFik is a technical blogging site helps techies and engineers to solve their day to day issues and also allows everyone to share knowledge and feedback. Please feel free to contact us at tekfik.rd@gmail.com if there is anything.

Leave a Reply

Your email address will not be published. Required fields are marked *