Tips: Execute scripts automatically on startup in Ubuntu

There are several ways to run a command or execute a shell script after Ubuntu Server finished booting up. Here is my simple and flexible way by creating systemd service:

1. Create a shell script.

For instance (go to folder function and run file handler):

#!/bin/bash
cd /home/hoant/go/function && ./handler

Save as startup.sh (or something as you want) and make it executable by chmod +x startup.sh

2. Create Systemd Service in Ubuntu

Create <service-name>.service file (replace service name with your service name) in /etc/systemctl/system/ (sudo is required) with a format like the following example:

[Unit]
Description=Example Service

[Service]
Type=simple
ExecStart=/path/to/script/file
User=hoant
Restart=always

[Install]
WantedBy=multi-user.target

Remember to

  • Replace/path/to/script/file with your proper path to startup.sh file
  • Set your actual username by replacing hoant in User field or remove User field if you want to run the service with user root (by default).
  • Restart=always mean your service will automatically restart if the program exits for whatever reason. If you don’t want to auto restart, then remove this field.

There are many other option fields, you can find out in detail here

3. Now, you have your own service and can play with it.

  • To start the service: sudo systemctl start <service-name>.service
  • To stop the service: sudo systemctl stop <service-name>.service
  • To check the status of the service: sudo systemctl status<service-name>.service

And finally, to start your services automatically after the system started, let enable it:

sudo systemctl enable <service-name>.service 

Enjoy!

Leave a Reply

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