Start Oracle VirtualBox VM with bash

I just came up with a way to start a Oracle VirtualBox VM with bash. Here is the code.

#!/bin/bash
vmname='Windows10'
cnt=$(VBoxManage showvminfo $vmname | grep -c 'running (since')
if [ $cnt -gt 0 ]; then
    logger "$vmname VM is already running"
else
    logger "Starting $vmname VM..."
    VBoxManage startvm $vmname --type headless
    logger "$vmname VM started successfully"
fi

The line #3 checks if it can find ‘running (since’ string in the standard output after running VBoxManage showvminfo $vmname and it assigns the occurrence count to cnt variable.

logger is the command you use to write log to /var/log/syslog. If the cnt value is greater than 0 (a positive number),  it writes out a message indicating that it’s already running in /var/log/syslog.

If it detects the VM is not running, it executes VBoxManage startvm $vmname –type headless to start the virtual machine.

This bash script could be run on startup or periodically in crontab or just be executed by hand.

Edit: If you add the following line to your crontab -e, it automatically starts the VM on startup.

@reboot /path/toyour/script/start-win10.sh

Enjoy!

Author: admin

A software engineer in greater Seattle area

Leave a Reply

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