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