Run Multiple Bash Scripts with Systemd (Step-by-Step)
Cat Administrator
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/foo@.service). 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%Irepresents the instance identifier passed during service activation.%irepresents 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}.serviceThis command creates symlinks for instances foo@1.service, foo@2.service, and foo@3.service based on the template.
Start the Instances:
Start individual instances with systemctl start, providing the instance identifier:
1systemctl start foo@1.service2systemctl start foo@2.service3systemctl start foo@3.serviceCreate 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=yesModify your .service units to be WantedBy=foo.target.
Reload and Start:
Reload systemd to apply changes:
1sudo systemctl daemon-reloadStart the target (if created):
1sudo systemctl start foo.targetTesting the Service
To test an instance, run:
1sudo systemctl start foo@1.serviceCheck the status:
1sudo systemctl status foo@1.serviceIf 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! 🚀🐧