There are many occasions when we need to run a bash script every time a Linux server boots. This can be particularly helpful for tasks such as mounting storage, starting services, and other essential Linux configurations.

Here are the steps to set up bash script execution on server boot using Debian 12.

Step 1 : Example you create the bash command on one file, create a bash file and write your needs on that bash file.

sudo vi /var/app/script/init.sh

Step 2 : Make sure the file is executable

sudo chmod +x /var/app/script/init.sh

Step 3 : Create a new file called init-boot.service in the /etc/systemd/system/ directory

sudo vi /etc/systemd/system/init-boot.service

Step 4 : Add the following content to the service file

[Unit]
Description=Run script init.sh at startup
After=network.target

[Service]
Type=oneshot
User=mylinuxuser
ExecStart=/bin/bash /var/app/script/init.sh
RemainAfterExit=true

[Install]
WantedBy=multi-user.target

Type=oneshot: Ensures the service runs the script once and then stops.

User=mylinuxuser: User who will be run the script.

RemainAfterExit=true: Keeps the service in active state after the script finishes execution.

Step 5, Save and close the file

Step 6, Reload systemd to recognize the new service:

sudo systemctl daemon-reload

Step 7, Enable the service to start at boot:

sudo systemctl enable init-boot.service

Step 8, Start the service immediately (optional):

sudo systemctl start init-boot.service

Step 9. Check the status of the service to ensure it is running correctly:

sudo systemctl status init-boot.service

This setup ensures that /var/app/script/init-boot.sh runs once every time the system boots, using the mylinuxuser user. The RemainAfterExit=true directive ensures that the service is marked as active after the script completes, preventing it from being restarted by systemd.

Leave A Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.