How to Run Shell Script as Systemd Service in Linux ?
Here, we will make a manual script which will act like a process to find disk utilization of the Linux system.
To begin, Make a bash script that redirects date and disk utilization in a file. You can create files in any location. We are going to make in executable directory /usr/bin:
$ sudo vim /usr/bin/script.shThen, Copy and paste the following script and save your file:
#!/bin/bash # Script generates disk utilization by the system and store in a file while true do date >> /var/storage-monitor.txt sudo du -sch / >> /var/storage-monitor.txt sleep 120 doneNext, Make the file executable by running the following command.
$ chmod +x /usr/bin/script.shNow, let’s 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:
$ vim /etc/systemd/system/monitor-disk.serviceAnd add the following details:
[Unit] Description=My disk monitoring service Documentation=https://www.kernel.org/ #After=networking.service [Service] Type=simple User=root Group=root TimeoutStartSec=0 Restart=on-failure RestartSec=30s #ExecStartPre= ExecStart=/usr/bin/script.sh SyslogIdentifier=Diskutilization #ExecStop= [Install] WantedBy=multi-user.targetWhat is going on here is:
- The [Unit] section consists of description, documentation details. Here we have mentioned ‘After’ which states the service that we are going to create must be running first.
- [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.
From https://linuxapt.com/blog/496-run-shell-script-as-systemd-service-in-linux