In this article you will learn how to run script ( python, bash etc. ) on startup on Ubuntu 20.04 Server/Desktop.
In this tutorial you will learn:
- How to create Systemd service unit
- How to create a simple disk space check script
- How to set permissions to Systemd service unit file
- How to set script permissions
- How to enable Systemd service unit to run at the system startup
Software Requirements and Conventions Used
Category | Requirements, Conventions or Software Version Used |
---|---|
System | Installed Ubuntu 20.04 or upgraded Ubuntu 20.04 Focal Fossa |
Software | N/A |
Other | Privileged access to your Linux system as root or via the sudo command. |
Conventions |
# – requires given linux commands to be executed with root privileges either directly as a root user or by use of sudo command$ – requires given linux commands to be executed as a regular non-privileged user |
How to run script on startup on Ubuntu 20.04 step by step instructions
The Ubuntu 20.04 is based on Systemd hence the simplest and recommended way to run a script on startup is to create a Systemd service file and execute any script such as bash, python etc, via this service during the system boot.
The below steps will show you to run an example bash script which reports disk space usage of the /home
directory and saves the report in the /root
directory every time the Ubuntu system boots.
- First, create a Systemd service file as in an example below:
[Unit] After=network.target [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 network connection. Other example could be mysql.target etc.
ExecStart: This field provides a full path to the actual script to be executed on startup
WantedBy: Into what boot target the systemd unit should be installedNOTE
For more information on how to create Systemd service unit execute theman systemd.unit
command. - Create a script to be executed on Ubuntu system startup. As specified in the above Step 1, the path and the name of the new script is
/usr/local/bin/disk-space-check.sh
.The below is an example of such script:
#!/bin/bash date > /root/disk_space_report.txt du -sh /home/ >> /root/disk_space_report.txt
- Set appropriate permissions for both, the Systemd service unit and script:
$ sudo chmod 744 /usr/local/bin/disk-space-check.sh $ sudo chmod 664 /etc/systemd/system/disk-space-check.service
- Next enable the service unit:
$ sudo systemctl daemon-reload $ sudo systemctl enable disk-space-check.service
-
Now you are ready to reboot your system. Once the system boots you should see the following file containing disk space usage within your
/root
directory:$ sudo ls /root/ disk_space_report.txt