Running Bash Shell Script as Systemd Service on Linux / 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/

while true
//your code
sleep 10

Allow the script to run:

$ chmod +x /usr/local/bin/

Create a unit file:

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

Description=My Test Bash Script

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 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 *