Writing startup scripts using init script method
- Published on
- 3 mins read
Creating systemd services has been goto startup scripts for the modern times, but there are times this method fails due to some reason, recently I wanted to write a startup script for my spot ec2 instance, So that whenever the machine reboots, the critical services like game-server, bot-server etc. should start with it.
But my game-server and bot-server relied on some third party tools, which took some time to load after system reboot, So I wasn't able to start those necessary services using systemd
.
So, I tried init script
method and fortunately this worked.
Here's step by step guide to make your own startup scripts with init script
method.
Instructions
Create a new script file, let's call it myscript, in the /etc/init.d/ directory:
sudo nano /etc/init.d/myscript
Add the following code to the
myscript
file:#!/bin/bash # chkconfig: 2345 99 01 ### BEGIN INIT INFO # Provides: myscript # Required-Start: $remote_fs $syslog # Required-Stop: $remote_fs $syslog # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 # Short-Description: Start My Script at boot time # Description: Enable service provided by My Script. ### END INIT INFO # chkconfig: 2345 20 80 # description: My Script # Source function library. . /etc/init.d/functions start() { echo "Starting My Script" su - ec2-user -c "/home/ec2-user/auto_start.sh" } stop() { echo "Stopping My Script" # Add any necessary stop actions here } case "$1" in start) start ;; stop) stop ;; restart) stop sleep 2 start ;; *) echo "Usage: $0 {start|stop|restart}" exit 1 esac
here
auto_start.sh
was the script, I wanted to run after system reboot.Save the file and make it executable:
sudo chmod +x /etc/init.d/myscript
Register the init script with the system:
sudo chkconfig --add myscript
Configure the init script to start automatically at system startup:
sudo chkconfig myscript on
Done :)
Now the content of auto_start.sh
will run whenever your system reboots, even if the processes in the script are dependent on some third party tools to load first.
I hope you found this helpful. Feedback are welcome. Thank you!!