Run a Script on Startup in Linux

Run a Script on Startup in Linux

To add a startup script on Linux that runs whenever the server is started or restarted, using systemd

First, your /path/to/startup_script.sh

#!/bin/bash

# Your commands here
echo "Server started at $(date)" >> /var/log/server_start.log
# Add any other startup tasks you need

make the script executable

sudo chmod +x /path/to/startup_script.sh

Create a new file in systemd service file

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

with following content

[Unit]
Description=Startup Script
After=network.target

[Service]
ExecStart=/path/to/startup_script.sh
User=root

[Install]
WantedBy=multi-user.target

Next enable and start the service

sudo systemctl daemon-reload
sudo systemctl enable startup_script.service
sudo systemctl start startup_script.service

Check service status

sudo systemctl status startup_script.service

08. Aug 2024