In this post, I will introduce three ways to create a startup script in Ubuntu: systemd (systemctl command), crontab (@reboot directive), shell startup script (.bash_login, .bashrc, ...).
Assume that the script to be run when the startup is at
Create systemd startup script
Create systemd unit
.service file in
/etc/systemd/system, lets call it
my-service.service. The content of this
my-service.service file should contain as follows
[Unit] Description=My custom startup script # After=network.target # After=systemd-user-sessions.service # After=network-online.target [Service] # User=spark # Type=simple # PIDFile=/run/my-service.pid ExecStart=/home/transang/startup.sh start # ExecReload=/home/transang/startup.sh reload # ExecStop=/home/transang/startup.sh stop # TimeoutSec=30 # Restart=on-failure # RestartSec=30 # StartLimitInterval=350 # StartLimitBurst=10 [Install] WantedBy=multi-user.target
Start/stop this service with
systemctl start my-service.service,
systemctl stop my-service.service.
To start this service when startup
systemctl enable my-service.service.
Refer to this digital ocean post for more detail on the systemd unit file structure.
Add startup crontab job
Replace the repeat section of crontab definition with
crontab -e, add this line
@reboot /home/transang/startup.sh. ( source).
However, this approach is not reliable. There is also a bug in some Debian variants. The behavior is inconsistent between reboot and shutdown/start. Thus, I will not go more specifically on when this crontab is executed, where it is placed, who the user is running it, whether this job is executed with sudoer privilege.
Create a shell startup script
Refer to this post to understand startup scripts and their execution order. Note that you should never rely upon that a bash startup script is executed whenever a graphical login appears or after you login because this behavior varies a lot on the graphical program, even version to version.