Merge VirtualBox Snapshots via Bash Script

Use case

My backup script automatically creates daily snapshots of each VM images (for incremental backups). Thus I have a huge amount of snapshots after a while. Unfortunately the VirtualBox-UI does not provide a method of removing/mergin all snapshots at once.


So I wrote a small script that is doing this job for me (and configured it via cronjob to be run once a week).
The code must be executed as sudo.

# Hello World
echo '========================================'
echo '= Bash version '${BASH_VERSION}'       ='
echo '= [CTRL] + [Z] to kill process         ='
echo '========================================'

# Exit with message and error code
function failure() {	
	echo ''
	echo 'ERROR:'$1
	echo ''
	exit 1

# Check whether this script got called as super user. If not, we can not 
# proceed.
if [ "$(whoami)" != "root" ]; then
	failure 'Aborting: You must be root to execute this script.'
# Get all users
declare -a users 	
tmp_users="$( getent passwd | grep /home/ | cut -d ':' -f 1 )"
for u in ${tmp_users}; do
	if [ -d "$tmp_dir" ]; then

# Do delete/merge all snapshots
for ((i=0;i<${#users[@]};i++)); do

	echo "> Processing user: ${users[i]}"

	# Get all installed VMs
	vms=$(su -c "VBoxManage list vms | sed -E 's/^\"(.*)\".*/\1/g'" -s /bin/sh ${users[i]})

	# Create new snapshot of each
	for vm_name in $vms; do 
		echo "> > Processing VM ${vm_name}.."

		# Loop through each snapshot and delete/merge it
		snapshots=$(su -c "VBoxManage showvminfo ${vm_name} --machinereadable | grep SnapshotName | cut -d '\"' -f2" -s /bin/sh ${users[i]})
		for snapshot_name in $snapshots; do 
			echo "> > > Merging snapshot: ${snapshot_name}.."
			snapshots=$(su -c "VBoxManage snapshot ${vm_name} delete ${snapshot_name}" -s /bin/sh ${users[i]})


The script tries to remove all snapshots of all images of all users.
In VirtualBox terms “removing an snapshot” actually means that they get merged into the main virtual file – without any loss of data.


Tagged with: , ,
Posted in Ubuntu, VirtualBox
One comment on “Merge VirtualBox Snapshots via Bash Script
  1. This blog post really grabbed my attention. With that said I am going to subscribe. Therefore I will get more updates on what you have to say. Please keep writing as I want to learn more.

Leave a Reply

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


Anti-spam protection

Prove that you are Human by typing the emphasized characters:

Protected by Gab Captcha 2

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>