How to Run Shell Script as Systemd Service in Redhat - CentOS

Systemd is a software application that provides an array of system components for Linux operating systems. It is the first service to initialize the boot sequence. This always runs with pid 1. This also helps use to manage system and application service on our Linux operating system.

You can also run any custom script as systemd service. It helps the script to start on system boot. This can be helpful for you to run any script which required to run at boot time only or to run always.

Example systemctl service file to start the ScriptService:

cd /etc/systemd/system

vi ScriptService.service

Change the values in the file sample below for ExecStart and ExecStop to point to the correct installation directory.

Sample systemctl ScriptService file:

#
[Unit]
Description=Example ScriptService
After=network.target

[Service]
ExecStart=/home/user/ScriptService.sh -start
ExecStop=/home/user/ScriptService.sh -stop
Type=forking

[Install]
WantedBy=default.target

Save the file and close it.

To start / stop / status the ScriptService :

Your system service has been added to your service. Let’s reload the systemctl daemon to read new file. You need to reload this deamon each time after making any changes in in ScriptService.service file.

sudo systemctl daemon-reload

Now enable the service to start on system boot, also start the service using the following commands.

sudo systemctl start ScriptService
sudo systemctl stop ScriptService

Once the ScriptService is started with the “systemctl start ScriptService” command, all script/db/app configured to autostart will be started by the ScriptService.

To run a script once during system boot time doesn’t required any infinite loop. Instead of the above script, you can use your shell script to run as Systemd service.

To enable the service to start at boot time:

sudo systemctl enable ScriptService

First of all, create a sample shell script to run always until the system is running. We will use bash while loop to run infinitely.

Add the following sample script:

#!/bin/bash

# Check OS Version
echo "Finding OS Codename..."

CODENAME='cat /etc/*-release | grep "VERSION="'
CODENAME=${CODENAME##*\(}
CODENAME=${CODENAME%%\)*}

echo "$CODENAME" > /tmp/OS-ver.log  # Create OS log in /tmp/ 

Save script and set execute permission.

sudo chmod +x /home/user/ScriptService.sh

Finally verify the script is up and running as a systemd service.

sudo systemctl status ScriptService.service

Output looks like below: