How to automatically execute shell script at startup boot on systemd Linux

/home/

/root/

Systemd service unit

disk-space-check.service

/etc/systemd/system/

[Unit] After=mysql.service [Service] ExecStart=/usr/local/bin/disk-space-check.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.

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

systemd.service

$ man systemd.service

Startup shell script

/usr/local/bin/disk-space-check.sh

#!/bin/bash date > /root/disk_space_report.txt du -sh /home/ >> /root/disk_space_report.txt

SUBSCRIBE TO NEWSLETTER

Subscribe to Linux Career NEWSLETTER and receive latest Linux news, jobs, career advice and tutorials.

Configure and Install

# chmod 744 /usr/local/bin/disk-space-check.sh

# chmod 664 /etc/systemd/system/disk-space-check.service # systemctl daemon-reload # systemctl enable disk-space-check.service Created symlink from /etc/systemd/system/default.target.wants/disk-space-check.service to /etc/systemd/system/disk-space-check.service.

# systemctl start disk-space-check.service # cat /root/disk_space_report.txt Thursday 7 July 11:30:25 AEST 2016 1.5G /home/

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 etc.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 check a disk space of adirectory during a boot time and write a report todirectory.First, we need to create a systemd startup script eg.and place it intodirectory. You can find the example of such systemd startup script below: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 seemanual page: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. The content of the script can be simple as:Before we reboot our system we need to make our script executable:Next, install systemd service unit and enable it so it will be executed at the boot time:If you wish to test your script before you reboot run:All ready. After rebooting your Linux system the above systemd unit will invoke shell script to be executed during the boot time.