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.

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

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/


Leave a Reply

Your email address will not be published.