Tips - How to automatically execute shell script at startup boot on systemd linux

Tips - How to automatically execute shell script at startup boot on systemd linux

The following config will discuss a basic example on how to execute shell script during a boot time on systemd Linux. There maybe various reason why you might want to execute shell script during Linux startup like for example to start a particular custom service, check disk space, create a backup …
Braden Collum©

The following example below will serve as a basic template to be later modified to suit your specific needs. In the example below we will force to change MAC address on eth1 interface.

  1. Systemd service unit
  2. Startup shell script
  3. Configure and Install

Systemd service unit

First, we need to create a systemd startup script ux_startup.service eand place it into /etc/systemd/system/ directory. You can find the example of such systemd startup script below:

   [Unit]
   Description=Start at startup.
   After=multi-user.target

   [Service]
   ExecStart=/opt/<path>/ux_startup.sh

   [Install]
   WantedBy=default.target
  • After: Instructs systemd on when the script should be run. In our case the script will run after mysql database has started. Other example could be network.target etc.
  • ExecStart: This field provides a full path the actual script to be execute
  • WantedBy: Into what boot target the systemd unit should be installed

The above is an absolute minimum that our systemd service unit should contain in order to execute our script at the boot time. For more information and options to be used see systemd.service man page:

    man systemd.service

Startup shell script

Next, we create our custom shell script to be executed during systemd startup. The location and script name is already defined by service unit as /opt/<path>/ux_startup.shh. The content of the script can be simple as:

#!/bin/sh
# Load ipset and iptable
ipset restore -! < /etc/ipset.up.rules
iptables-restore < /etc/iptables.up.rules

Configure and Install

Before reboot our system we need to make our script executable:

   chmod 744 /opt/<path>/ux_startup.sh

Next, install systemd service unit and enable it so it will be executed at the boot time:

   chmod 664 /etc/systemd/system/ux_startupe.service
   systemctl daemon-reload
   systemctl enable ux_startup.service

If you wish to test your script before you reboot run:

    systemctl start ux_startup.service

All ready. After rebooting your Linux system the above systemd unit will invoke shell script to be executed during the boot time.



Share on :