Start or Stop a script on Boot and Shutdown

Last modified
Friday, March 17, 2017 - 11:39

Run a script when the system starts up or reboots on Ubuntu.

1) Create script, on this example I'm starting the gluu-server service as the root user

$sudo nano /etc/init.d/MyScriptName

Copy/paste the following script, update accordingly:

#! /bin/sh
# /etc/init.d/MyScriptName
#

case "$1" in
  start)
    echo "Attempting to Start Gluu Server..."
    sudo -H -b service gluu-server start
    ;;
  stop)
    echo "Attempting to Stop Gluu Server..."
    sudo -H service gluu-server stop
    ;;
  *)
    echo "Usage: /etc/init.d/MyScriptName {start|stop}"
    exit 1
    ;;
esac

exit 0

2) Give the script executable permission

$sudo chmod +x /etc/init.d/MyScriptName

3) Tell script to run at startup. This tells the script be the first to shutdown and the last to startup.

$sudo update-rc.d MyScriptName defaults 99 01

If you want to remove the script from the system:

$update-rc.d -f MyScriptName remove
$update-rc.d MyScriptName stop levels ## Deprecated on Ubuntu 16.04

Another example of usage is booting a virtual machine using VMware or VirtualBox on the following script I am executing a virtualbox script to start and stop a virtual machine when my host computer starts or shuts down:

#! /bin/sh

### BEGIN INIT INFO
# Provides: StartGluu
# Required-Start: $remote_fs $syslog
# Required-Stop: $remote_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Start Gluu Server VM at Boot
# Description: Star Gluu Server.
### END INIT INFO

# /etc/init.d/StartVM
#
#Edit these variables!
VMUSER=andres
VMNAME="Gluu Server"

case "$1" in
  start)
    echo "Starting VirtualBox VM..."
    #sudo -H -b -u $VMUSER /usr/bin/VBoxVRDP -s "$VMNAME"
    sudo -H -u  $VMUSER nohup /usr/bin/VBoxHeadless -startvm "$VMNAME" < /dev/null > /dev/null 2>&1 &
    #sudo -H -u  $VMUSER /usr/bin/VBoxHeadless -startvm "$VMNAME" &
    ;;
  stop)
    echo "Saving state of Virtualbox VM..."
    sudo -H -u  $VMUSER /usr/bin/VBoxManage controlvm "$VMNAME" savestate
    #nohup VBoxHeadless -startvm "openid_connect" < /dev/null > /dev/null 2>&1 &
    #sudo -H -u  $VMUSER /usr/bin/VBoxManage controlvm "$VMNAME" poweroff
    #sudo -H -u  $VMUSER /usr/bin/VBoxManage controlvm "$VMNAME" acpipowerbutton
    ;;
  *)
    echo "Usage: /etc/init.d/StartVM {start|stop}"
    exit 1
    ;;
esac

exit 0

 

Add new comment

This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.