How to run a shell script at startup

The easiest way to do have a shell script run on startup is to create a a systemd startup service. This ensures that all prerequisites are loaded prior. To create one, follow the below steps.

Create a systemd unit file with .service extension in /etc/systemd/system, for example /etc/systemd/system/hddcheck.service, with the following content:

[Unit]
Description=Service description

[Service]
ExecStart=/home/ryan/hddcheck.sh #Example

[Install]
WantedBy=multi-user.target

After this, assuming that your script exists and is runnable, you should be able to start the service with: systemctl start hddcheck. To enable this to startup at boot use: systemctl enable hddcheck.

Explanation

The main takeaways here the code snippets: ExecStart=/home/ryan/hddcheck.sh and WantedBy=multi-user.target. The first of these simply tells the service what to execute when started, similar paramaters exist such as ExecReload and ExecStop. The second one, WantedBy=multi-user.target, effectively waits until the system is ready to start doing stuff a normal user would do. This means that the network services are ready e.t.c.

Mastodon