Waiting for VirtualBox guests to close before reboot or shutdown

See this and this. Basically:

vim /etc/init.d/virtualbox
chmod +x /etc/init.d/virtualbox
update-rc.d virtualbox defaults

The /etc/init.d/virtualbox script should look like this:

#!/bin/sh

# 2017-08-07 jj5 - SEE: How make Debian wait for all VirtualBox guests to
# stop during shutdown/reboot?: https://superuser.com/a/929292/615689

### BEGIN INIT INFO
# Provides:          virtualbox_start_and_stop
# Required-Start:    $local_fs $network
# Required-Stop:     $local_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: 
# Description:       Start virtualbox on boot, and shutdown safely on shutdown/reboot.
### END INIT INFO

case "$1" in
  start)
    echo "Starting Virtualbox "

    # Do whatever to start or resume your virtualbox instances.
    # Perhaps look for a txt file someplace with VMs that need to be
    # restarted or resumed... then start 'em.
    ;;
  stop)
    echo "Stopping Virtualbox"

    # Do something to either shutdown or savestate your virtualbox instances.
    # maybe also save the instances that should be resumed into a txt file
    # someplace for the start method above.

    # 2017-08-07 jj5 - SEE:
    # https://askubuntu.com/a/457564

    # 2017-08-07 jj5 - NOTE: You should make sure that ACPI Shutdown actually
    # shuts down the guest...
    # 2017-08-07 jj5 - SEE: Force Ubuntu Desktop to shutdown on power button:
    # https://www.progclub.org/blog/2017/08/07/force-ubuntu-desktop-to-shutdown-on-power-button-keypress-acpi-shutdown/

    while [ -n "$( sudo -u jj5 VBoxManage list runningvms )" ]; do

      sudo -u jj5 VBoxManage list runningvms \
        | sed -r 's/.*\{(.*)\}/\1/' \
        | xargs -L1 -I {} sudo -u jj5 VBoxManage controlvm {} acpipowerbutton;

      sleep 1;

    done;

    ;;
  *)
    echo "Usage: /etc/init.d/virtualbox {start|stop}"
    exit 1
    ;;
esac

exit 0

You may also need to Force Ubuntu Desktop to shutdown on power button keypress

Bash wait

Today I learned about the ‘wait’ command. It waits for background processes to terminate before returning, so you can fire off a bunch of jobs to be run in parallel and then wait for all of them to complete before continuing, like in this take-ownership.sh script I wrote tonight:

#!/bin/bash
if [ -n "$1" ]; then
  pushd "$1" > /dev/null 2>&1
  if [ "$?" -ne "0" ]; then
    echo "Cannot change dir to '$1'.";
    exit 1;
  fi
fi
sudo chown -R jj5:jj5 . &
sudo find . -type d -exec chmod u+rwx {} \; &
sudo find . -type f -exec chmod u+rw {} \; &
if [ -n "$1" ]; then
  popd > /dev/null 2>&1
fi
wait
exit 0