Sometimes it might be required to run scripts at startup. This is useful if you want to automate tasks like running updates, installing packages or even settings default routes. Here we will create a new service and invoke a custom bash script to set static routes in a VPS. Your script can do anything as long as it’s bash and coded correctly. First, we will create a new service. Our service will be called f2h.service. You can name your server anything but it must end .service.
Most Linux distributions use systemd to manage services so this is an excellent and easy way to configure custom functions. Systemd manages startup functions and does important things like raising network interfaces. It’s present in all of the major OS distributions by default so requires very little configuration by end-users. We’re going to create a new service in the next steps and code a simple script to run at startup.
Create Service
System services are usually located in /etc/systemd/system/ We are using an Ubuntu NVMe VPS but the same is true for Debian and CentOS. Create a new file with your service name and enter the code.
nano /etc/systemd/system/f2h.service
[Unit]
After=cloud-init.service
[Service]
ExecStart=/F2H/routes.sh
[Install]
WantedBy=default.target
Unit = This area stipulates when our custom bash script will be run. So, our script is set to run after Cloud-init. You can switch this to a different service like the networking.service if required.
Service = This is the path to our bash script
Install = This is the target the service is installed to. But, do not edit this.
Now chmod the file 664
chmod 664 /etc/systemd/system/f2h.service
Create Bash Script
So, this is the file that will contain our script. The location of our script is going to be /F2H/routes.sh as specified in the service file above.
nano /F2H/routes.sh
#!/bin/bash
ip route add 10.10.10.1 dev eth0
ip route add default via 10.10.10.1
This script configures a static route to our internal gateway. Your script can do anything you want. Now chmod the file 744.
chmod 744 /F2H/routes.sh
Reload Services
Finally, we reload the daemon and enable our new service.
systemctl daemon-reload
systemctl enable f2h.service
That’s it. We have created a new service and configured a custom bash script to run at startup.
How was this article? How To Run Scripts At Startup
You might also like
More from All About Linux
How To Open Port FirewallD and Close Port FirewallD -CentOS 7
Open And Close Ports In FirewallD - Manage Zones In FirewallD Like IPtables, FirewallD is a Linux firewall that filters packets …
How To Add Bootsplash Image To Your OS Template
Instead of the default black screen. When creating an OS template you can choose to add a bootsplash image to …
Ping Multiple IPs and Subnets With FPING
Recently we showed you how you could ping multiple IPs with a simple bash script. Now we are going to …