Have a command run at boot
In 2024, we use systemd
for this in all major distributions. There are other distributions that do not like systemd
and are still using older initialization ("init") systems like "Sys-V" or alternatives like "runit". If you are unsure, you're probably running systemd
and should follow this guide. You would usually know if you're using an alternative.
- Debian-based OS (Debian, Ubuntu, Mint, Raspbian)
- RedHat-based OS (RHEL, CentOS, Rocky, Alma, Suse)
- Pick a service name, like "script" or "server". We will use NAME to be a placeholder but you should swap in your service name
- Create or edit a file at
/etc/systemd/system/NAME.service
(See contents below) - Add more environment variables, edit the parameters as needed.
- You may execute a script file (make sure it's executable!) or a command like you would on the command line
- If you only want the script to run once, instead of automatically restarting, switch "simple" to "oneshot"
- Run
sudo chmod 660 /etc/systemd/system/NAME.service
- Run
sudo systemctl daemon-reload
to re-scan the files (we need to do this because you just created/edited one) - Run
sudo systemctl start NAME
- Verify your service started correctly with
systemctl status NAME
- View logs if needed with
sudo journalctl -n 20 -u NAME
(returns the latest 40 lines) - If you need to, you can restart the service with
sudo systemctl restart NAME
- Run
systemctl enable NAME
to start this service automatically on boot/startup - Test it by rebooting your system now