LinuxScripting

How To Run Scripts At Startup In a Linux Server

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 run a script 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 <em>/etc/systemd/system/</em>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 run a script at startup.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button