Run Multiple Bash Scripts with Systemd (Step-by-Step)
![Abdul Aziz](/cat-devops.jpg)
Cat Administrator
![Run Multiple Bash Scripts with Systemd (Step-by-Step)](/_astro/how-to-run-multiple-bash-scripts-with-systemd.oz8SLeTq_Z25QuxP.webp)
This tutorial guides you through setting up a systemd service to efficiently run multiple Linux Bash scripts. You’ll learn how to create a service that automatically starts, stops, and restarts your scripts. Let’s dive in!
Prerequisites
- Linux System: You need a Linux system (e.g., Ubuntu, CentOS, Debian) with systemd installed.
- Bash Scripts: Prepare the Bash scripts you want to run. Ensure they are executable and located in a specific directory (e.g.,
/path-to-bash-script/
).
Steps to Create the Systemd Service
Create a Template Unit File:
Decide how many script instances you need (e.g., three instances).
Create a template unit file (e.g., /etc/systemd/system/[email protected]
). Note the ”@” symbol, which allows for parameterization.
Add the following content to the file, replacing placeholders with your information:
1[Unit]2Description=Running Bash Script for %I3
4[Service]5Type=simple6ExecStart=/bin/bash /path-to-bash-script/script-name-%i.sh7ExecStop=/bin/bash /path-to-bash-script/script-name-%i.sh8Restart=on-failure9
10[Install]11WantedBy=foo.target
%I
represents the instance identifier passed during service activation.%i
represents the instance identifier converted to lowercase.
Replace /path-to-bash-script/
and script-name-
with your actual paths and script name prefixes.
Enable Instances:
Enable the desired number of instances using systemctl enable
:
1systemctl enable foo@{1..3}.service
This command creates symlinks for instances [email protected]
, [email protected]
, and [email protected]
based on the template.
Start the Instances:
Start individual instances with systemctl start
, providing the instance identifier:
123
Create a Target Dependency:
To group instances under a common target for easier management, create a target unit file (e.g., /etc/systemd/system/foo.target
):
1[Unit]2Description=foo target3Requires=multi-user.target4After=multi-user.target5AllowIsolate=yes
Modify your .service
units to be WantedBy=foo.target
.
Reload and Start:
Reload systemd to apply changes:
1sudo systemctl daemon-reload
Start the target (if created):
1sudo systemctl start foo.target
Testing the Service
To test an instance, run:
1
Check the status:
1
If everything is configured correctly, you’ll see the output of your Bash script.
Conclusion
Congratulations! You’ve successfully set up a systemd service to manage multiple Bash script instances. This approach provides a structured way to automate and control your scripts.
Remember to adapt the paths, filenames, and instance numbers to your specific needs. Happy scripting! 🚀🐧