Thursday, April 30, 2020

Running a command at startup in Ubuntu

An example how to automatically run a command at startup. To run a command a new service is needed to launch the script where the desired commands are.


1. Create a script

sudo nano /home/[username]/script/ntpstart.sh

#!/bin/sh
sudo service ntp restart

2. Make the script executable

sudo chmod 775 /home/[username]/script/ntpstart.sh

3. In the /etc/systemd/system create a service

sudo nano /etc/systemd/system/ntpstart.service

[Unit]
Description=Start NTP

[Service]
Type=oneshot
ExecStartPre=-/bin/sleep 60
ExecStart=/bin/sh /home/[username]/script/ntpstart.sh

[Install]
WantedBy=multi-user.target

4. Enable the ntpstart.service

systemctl enable ntpstart.service