How can I run a script on startup on Ubuntu Server 17.10?
Put the script in the appropriate user's cron
table (i. e. the crontab) with a schedule of @reboot
.
A user can edit its cron
table with crontab -e
.
An example which will run /path/to/script.sh
at startup:
@reboot /path/to/script.sh
If you need to run it as root, don't use @reboot sudo /path/to/script.sh
;
use sudo crontab -eu root
to edit root's crontab.
See also: crontab(1), cron(8), crontab(8)
Ubuntu 15.04 and forward by default uses something called systemd
, which is a program (of sorts) that automates startup services and procedures. You can make your own and add it to the list of startup services with only a little bit of effort.
Basic Systemd Service
This is a barebones .service
file that could be used to launch my python gui server (could've been a shell script, it doesn't matter):
[Unit]
Description=Python GUI Server
[Service]
ExecStart=/home/pi/software/GUI_POE.py &
[Install]
WantedBy=multi-user.target
The Description
option is any string that described what the service is or does.
The ExecStart
option specifies the command to execute. Here, I give a path to an executable python script and use the &
token to run it in the background.
The WantedBy
option specifies precedence, based on what target wants to use this service. If you don't need your service to run at any very specific time, then just set it to multi-user.target
.
Basic Procedure
Write the script you wish to run at startup using
nano
or any editor of your choice. Make sure you include the proper shebang at the very top of the file (#!/bin/bash
for bash scripts), and give it executable permissions withchmod
.Simply write up your service in a file named my_service.service, and then copy it into the proper directoy with
cp my_service.service /lib/systemd/system/
.Start your service:
sudo systemctl start my_service.service
. This launches whatever script you told your service to run. The same command with "stop" instead of start will turn it off.Add your service to the start-up process:
sudo systemctl enable my_service.service
. To remove it, simply replace "enable" with "disable" in the same command.
And that's it! Keep in mind that your script will automatically be run with root permissions, as that's default in systemd services.
My Simple Example (Full)
For reference, here's a simple systemd service I have that launches a simple Python GUI Server using Dash:
[Unit]
Description=Python GUI Server
After=network-online.target
[Service]
Type=simple
WorkingDirectory=/home/pi/software
ExecStart=/home/pi/software/GUI_POE.py &
Restart=always
RestartSec=15s
KillMode=process
TimeoutSec=infinity
User=pi
Group=pi
[Install]
WantedBy=multi-user.target
This example service uses a Python3 script but the formula is the exact same for a shell script.
Further reading can be found at this excellent tutorial by DigitalOcean, and this AskUbuntu thread with an excellent answer that helped me learn systemd. Hope this helps!