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:
%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
:
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:
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
):
Modify your .service
units to be WantedBy=foo.target
.
Reload and Start:
Reload systemd to apply changes:
Start the target (if created):
Testing the Service
To test an instance, run:
Check the status:
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! 🚀🐧