How to Run Scripts at startup?

Scripts are required to run upon startup on occasion. It is a good option to automate operations like performing updates, installing packages, or even setting default routes. We’ll create a new service and run a custom bash script to set static routes in a VPS. Your script can do anything as long as it’s written in bash and is properly coded. We’ll start by creating a new service. f2h.service will be the name of our service. Your server can have any name you like, but it must finish in. service.

Because systemd is used to handle services in most Linux distributions, this is a great and simple approach to set up custom functions. Systemd controls startup functions and performs critical tasks such as raising network interfaces. It comes pre-installed in all major OS variants and requires minimal end-user configuration. We’ll build a new service and write a simple startup script in the next few steps.

Creating Service

/etc/systemd/system/ is where system services are normally found. We’re utilizing an Ubuntu NVMe VPS, although Debian and CentOS are also viable options. Create a new file with the name of your service and the code.

nano /etc/systemd/system/f2h.service
[Unit]
After=cloud-init.service
[Service]
ExecStart=/F2H/routes.sh
[Install]
WantedBy=default.target

This section specifies when our custom bash script will be executed. So, after Cloud-init, our script is configured to run. If necessary, you can change this to another service, such as networking. service.

The path to our bash script is called service.

Install = The service’s installation target. However, this should not be edited.

Now chmod the file 664:

chmod 664 /etc/systemd/system/f2h.service

Creating Bash Script

So, this is the file in which our script will be stored. Our script will be located at /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

A static route to our internal gateway is configured by this script. You have complete control over your script.

Now change the file’s permissions to 744:

chmod 744 /F2H/routes.sh

Reloading Services

systemctl daemon-reload 
systemctl enable f2h.service

That is all there is to it. We’ve constructed a new service and set it to start with a custom bash script.