Running Bash Shell Script as Systemd Service on Linux

PowerADM.com / Linux / Running Bash Shell Script as Systemd Service on Linux

On Linux, you can run a bash script as a service via systemd (instead of using the cron scheduler). This allows you to ensure that the script is always running, run the bash script on startup, check its health, and take advantage of other systemd benefits.

Create an SH script file:

$ mcedit /usr/local/bin/myscript.sh

#!/bin/bash
while true
do
//your code
sleep 10
done

Allow the script to run:

$ chmod +x /usr/local/bin/myscript.sh

Create a unit file:

$ sudo mcedit /etc/systemd/system/myscript.service

[Unit]
Description=My Test Bash Script
After=network.target
[Service]
Type=simple
ExecStart=/usr/local/bin/myscript.sh
[Install]
WantedBy=multi-user.target

running bash script in systemd

If the script interacts with the network, it must be run after the network has been initialized. This is made possible by the After=network.target option.

You can configure various options in the [Service] section.:

  • Type – defines the type of service. The default service type is simple. The oneshot type means that the service should perform a single task and exit;
  • ExecStop – set the command to be executed when the service stops.;
  • RemainAfterExit=true specifies that even though the process has exited, systemd will consider the service active.

Update systemd configuration:

$ systemctl daemon-reload

Enable autostart for the service and start it:

$ systemctl enable myscript.service
$ systemctl start myscript.service

Check that the service is running:

$ systemctl status myscript.service
Leave a Reply

Your email address will not be published. Required fields are marked *