How to create a custom systemd service file

dos2unix

Well-Known Member
Joined
May 3, 2019
Messages
2,358
Reaction score
2,045
Credits
18,058
Create or Identify Your Bash Script: Make sure you have a Bash shell script that you want to run. If it's not already in place, create one and make it executable by running chmod +x your_script.sh in the terminal. Typically you will want to make the permissions so non-root users can't do anything with this file.

Create a systemd Service File:

Open a text editor to create a service unit file with a .service extension. You can use a command-line text editor like nano or vim. For example:

sudo nano /etc/systemd/system/your_script.service
Replace your_script with a meaningful name for your service. You can name this anything. Halloween.service if you want.

Edit the Service File:

Add the following lines to your service file. Modify the ExecStart line to point to the location of your Bash script:
---------------------------------------------------------------------------

[Unit]
Description=Your Script Description

[Service]
Type=simple
ExecStart=/path/to/your_script.sh
Restart=always

[Install]
WantedBy=multi-user.target

-------------------------------------------------------------------------

Description: Provide a description for your service.
ExecStart: Set the full path to your Bash script.
Restart: This line specifies when the service should be restarted. In this example, it's set to always.
Reload systemd:

After creating the service file, you should reload the systemd configuration to make it aware of the new service:

sudo systemctl daemon-reload

To enable your service so that it starts at boot, use the following command:

sudo systemctl enable your_script.service

To start the service immediately, use:

sudo systemctl start your_script.service

You can check the status of your service to ensure it's running without errors:

sudo systemctl status -l your_script.service
This command will display information about the service, including its status and any recent logs.

Your bash script can be pretty much anything a bash script does.

#!/bin/bash
Echo "Checkout Linux.org today!" > /some/text_file.text
# Sleep for five minutes, then print it again"
sleep 300
/path/to/your_script.sh

That's a silly example, but it gets the point across.

If at some point you don't want this to run anymore, Just do the following.

systemctl stop your_script.service

To keep it from automatically starting at next reboot.

systemctl disable your_script.service
 
Last edited:


Latest posts

Top