How to Run a Script Before Shutdown Under Systemd

How to Run a Script Before Shutdown Under Systemd

Have you ever found yourself in need of ensuring that a specific task or script is executed every time before your system shuts down?

Whether it’s backing up essential files, performing cleanup operations, or any other crucial process that you want to guarantee occurs before your computer powers off, it may seem like a daunting challenge.

Fortunately, there is a straightforward solution: Systemd, a Linux system and service manager.

With Systemd, running a script before shutdown becomes easily achievable. In this article, we will guide you through the process, enabling you to seamlessly incorporate pre-shutdown scripts into your system.

Let’s dive right in!

What is Systemd?

Systemd is a powerful service manager that has replaced the traditional init system in Linux. It simplifies various tasks, including managing system startup sequences, configurations, user sessions, and network connections.

One of the notable advantages of systemd is its ability to provide flexibility when it comes to executing custom scripts before shutdown.

Whether you need to execute backups, perform cleanup operations, or carry out any other essential tasks, systemd empowers you to easily incorporate these actions into the shutdown process.

Why Run a Script Before Shutdown?

Running a script before shutdown serves several important purposes. The primary objective is to ensure that specific activities are completed before your system goes offline. Here are some key reasons why executing a script before shutdown is beneficial:

  1. Enables automation of system cleanup tasks.
  2. Helps in the proper closing of application processes.
  3. Facilitates customized log management during the shutdown.
  4. Helps prevent data corruption or loss.

Continue reading to learn about the prerequisites needed to run a script before shutdown under systemd. Also, follow the detailed steps provided for a seamless result.

What You’ll Need

Before we proceed with creating and running a script before shutdown under systemd, please ensure you have the following prerequisites:

  • A Linux system with Systemd installed (guide).
  • Basic understanding of Linux commands and text editors (guide).
  • Root or sudo user access (guide).
  • Familiarity with scripting in the Linux environment (guide).

Note: Most recent Linux distributions come with systemd by default. If your device is missing one, we suggest upgrading to the latest version rather than installing systems.

If you have all the above requirements, continue reading and learn how to run a script before shutdown under the systemd by following the steps below.

How to Run a Script Before Shutdown Under Systemd: Step-by-Step

Step 1: Create a Sample Script

  1. To run a script before shutdown using systemd, we first need to create a shell script. Let’s call it “shtdwn_script.sh“. Here’s how you can create the script using the vim editor:
sudo vim /usr/lib/systemd/system-shutdown/shtdwn_script.sh
Run a Script Before Shutdown Under Systemd 1
  1. To ensure that it is not stopped by the shutdown process, the new script (shtdwn_script.sh) must run for 1 minute in a loop. The plan is to delay shutting down the computer until the script has finished running. For the script (shtdwn_script.sh) to work, add the following lines:
#!/bin/bash
counter=0
 for ((i=1; i<=3; i++)); do 
sleep 1m 
((counter++))
echo ""
done
Run a Script Before Shutdown Under Systemd 2
    1. After adding the lines to the shtdwn_script.sh file in the vim editor, type “: to open the prompt bar. If you have done it right, you can see the prompt bar at the bottom left corner of the window, where you must type “wq” to save and exit the file (as shown in the screenshot below):
    Run a Script Before Shutdown Under Systemd 3
    1. After the shtdwn_script.sh file is saved successfully, provide executable permissions using the following command:
    sudo chmod +x /usr/local/bin/shtdwn_script.sh 

    Ensure you don’t miss providing executable permissions, as the script doesn’t function when tried to execute.

    Step 2: Create Unit File to Run Script with Systemd

    1. For the script (shtdwn_script.sh) we have created to work, creating a systemd unit file is necessary, because it is responsible for calling the script and executing it. For this purpose, create run-before-shutdown.service under the directory /etc/systemd/system. Use the following command to create a new system unit file using vim:
    sudo vim /etc/systemd/system/run-before-shutdown.service
    1. Add the lines below once you have successfully created the run-before-shutdown.service systemd unit file:
    How to Run a Script Before Shutdown Under Systemd
    1. Ensure that the values are as follows “Before=shutdown.target” and “TimeoutStartSec=0” for the directives. Now, save and exit the systemd unit file by typing “:wq” in the prompt bar and proceed further.
    2. Before proceeding, reload the systemd configuration to recognize the new unit file we created using the following command:
    sudo systemctl daemon-reload 

    Step 3: Test Systemd Unit File

    1. At this stage, you have successfully created a script and a systemd unit for it. However, you must enable the script to start automatically the next time the system is powered on. Use the following commands to enable and start the service:
    sudo systemctl enable run-before-shutdown.service
    sudo systemctl start run-before-shutdown.service
    1. If you want to verify if your script is working properly, use the below command. If you have done everything according to the steps, you will see an output stating that the service is loaded and enabled (as shown in the screenshot below): 
    Run a Script Before Shutdown Under Systemd 4
    1. If you find an error or the status displays that the service isn’t loaded or enabled, create a new script and systemd unit file.
    2. After verifying that the service is loaded and enabled, you can run the shutdown command below to verify that the script is active before the system shuts down:
    sudo poweroff
    1. On running the command, you’ll notice that the shutdown procedure will be delayed by 60 seconds before the system finally turns off.

    What to Do if You Cannot Run a Script Before Shutdown Under Systemd?

    As we are working with systemd, it is common to face issues, and unfortunately, some problems hide and don’t display right away until tested.

    Here are a few possible troubleshooting steps for the common issues you can consider checking out.

    • If the script fails to run, check the file permissions and make sure the script is executable.
    • If the service fails to start, validate your unit file’s syntax and ensure there are no incorrect or missing directives.
    • Ensure that the script does not require interaction. Systemd services are not attached to a terminal and cannot handle interactive scripts.

    Conclusion

    Understanding how to execute a script before shutdown using Systemd provides access to a robust and flexible system for managing system processes. Using systemd, you can ensure that crucial operations are carried out correctly and efficiently even when the system is turning off.

    Remember that you might make mistakes and face errors while working with systemd. For this purpose, refer to the troubleshooting steps provided.

    However, if you continue to experience errors or need further explanation or solutions, we recommend reaching out to Ubuntu Forums. The Ubuntu Forums serve as an invaluable resource, providing a community of knowledgeable individuals who can offer assistance and guidance in resolving any issues you may encounter.


    Related Posts