Run a Shell Script as Systemd Service in Linux 


In this post,I will make a manual script and register it as a SystemD Service in Linux.

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.

We 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


 
1) Create a script to monitor file system space

$ sudo vi /usr/bin/filesystem_check.sh
Then, Copy and paste the following script and save your file:

#!/bin/bash
# Script check filesystem utilization every 120 seconds store in a file
while true
do
date >> /var/log/fs-monitor.txt
sudo df -h  >> /var/log/fs-monitor.txt
sleep 120
done

 
2) Make the file executable by running the following command.

$ chmod +x /usr/bin/filesystem_check.sh

3) Make a service for running the script. 
Just create a file in the following directory. Note you can give any name but it must end with .service extension:

$ vi /etc/systemd/system/fs-monitor.service
And add the following details:

[Unit]
Description=FS monitoring service
Documentation=https://funoracleapps.com/

[Service]
Type=simple
User=root
Group=root
TimeoutStartSec=0
Restart=on-failure
RestartSec=30s
#ExecStartPre=
ExecStart=/usr/bin/filesystem_check.sh
SyslogIdentifier=Diskutilization
#ExecStop=

[Install]
WantedBy=multi-user.target


Explanation

The [Unit] section consists of description, documentation details etc

[Service] Section defines the service type, username, group, what to do in failure, restart timeout. The main is 'ExecStart' which says to start our script file. You can also define 'ExecStartPre' to define anything before the actual script file.'SyslogIdentifier' is the keyword to identify our service in syslog. Similarly, ExecStop is the instruction to say what to do to stop the service.

[Install] section is used to define different levels of target in the system.


4) Save the file and start the service using the systemctl command:

$ systemctl start fs-monitor.service
$ systemctl status fs-monitor.service




5) Verify that your script and check log file:

$ cat /var/log/fs-monitor.txt

6)Enable or disable to start at system boot

$ systemctl enable fs-monitor.service



$ systemctl disable fs-monitor.service

 
7) Stopping and Restarting Services

$ systemctl stop fs-monitor.service
$ systemctl restart fs-monitor.service





If you like please follow and comment