Creating an Auto Start/Stop Script for Virtualbox

Here is a script for auto starting/stopping Virtualbox VMs.

Text Box

#!/bin/bash
#
#This init script autostarts necessary vms at boot
#and saves running vms on shutdown
# Sed explanation: sed -e 's/^.//' -e 's/.$//'
#   1.  -e means to allow multiple arguments in a single sed command
#   2.  's/^.//' means to substitute (s) / at the beginning of the line (^), any character (.) / [substitute with nothing] /
#   3.  's/.$//' means to substitute (s) / any character (.), at the end of the line / [substitute with nothing] /
VBOXUSER=vbox
RUNNINGVMS=$(sudo -H -u $VBOXUSER vboxmanage list runningvms | cut -d " " -f1 | sed -e 's/^.//' -e 's/.$//')
STOPPEDVMS=$(sudo -H -u $VBOXUSER vboxmanage list vms | cut -d " " -f1 | sed -e 's/^.//' -e 's/.$//')
case "$1" in
 start)
       for i in $STOPPEDVMS
               do
                       echo "Starting" $i "VM"
                       sudo -H -u $VBOXUSER vboxmanage startvm $i --type headless
                       sleep 5
               done
   ;;
 stop)
       for i in $RUNNINGVMS
               do
                       echo "Saving state of" $i "VM"
                       sudo -H -u  $VBOXUSER vboxmanage controlvm $i savestate
               done
   ;;
 *)
   echo "Usage: /etc/init.d/startvm {start|stop}"
   exit 1
   ;;
esac
exit 0

To add this script as a startup script, place it in the /etc/init.d/ folder, then run: update-rc.d [name of the script] defaults 99 01