Created
June 25, 2012 13:31
-
-
Save senko/2988592 to your computer and use it in GitHub Desktop.
Easy VirtualBox VM handling for the command line
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash -e | |
# | |
# Easy VirtualBox VM handling from the command line | |
BASE_TEMPLATE="<uid-of-template-vm>" | |
function show_help() { | |
echo "Usage: $0 [cmd]" | |
echo "Valid commands:" | |
echo " list List available virtual machines" | |
echo " status List running virtual machines" | |
echo " start <vm> Start virtual machine <vm>" | |
echo " stop <vm> Stop (save state) of virtual machine <vm>" | |
echo " create <vm> Create a new machine based on base template" | |
echo " destroy <vm> Destroy virtual machine <vm>" | |
echo "" | |
echo "Base template: " $BASE_TEMPLATE | |
} | |
function list_vms() { | |
echo "Available virtual machines:" | |
vboxmanage list vms | |
} | |
function list_running() { | |
echo "Running virtual machines:" | |
vboxmanage list runningvms | |
} | |
function check_exists() { | |
list_vms | grep -qF "\"$1\"" | |
} | |
function check_running() { | |
list_running | grep -F "\"$1\"" | |
} | |
function start_vm() { | |
if ! check_exists "$1"; then | |
echo "Virtual machine $1 doesn't exist" | |
exit -1 | |
fi | |
if check_running "$1"; then | |
echo "Virtual machine $1 already running" | |
exit -1 | |
fi | |
vboxmanage startvm --type headless "$1" | |
} | |
function stop_vm() { | |
if ! check_exists "$1"; then | |
echo "Virtual machine $1 doesn't exist" | |
exit -1 | |
fi | |
if ! check_running "$1"; then | |
echo "Virtual machine $1 isn't running" | |
exit -1 | |
fi | |
vboxmanage controlvm "$1" savestate | |
} | |
function clone_vm() { | |
read -sp "Create a new virtual machine named '$1' [y/N]? " -N 1 TMP | |
echo "" | |
if [ "$TMP" == 'y' -o "$TMP" == 'Y' ]; then | |
vboxmanage clonevm "$BASE_TEMPLATE" --mode all --options keepnatmacs --name "$1" --register | |
fi | |
} | |
function destroy_vm() { | |
echo "No way Jose. If you're really sure, destroy it via the GUI" | |
exit -1 | |
} | |
if [ "$1" == "list" ]; then | |
list_vms | |
elif [ "$1" == "status" ]; then | |
list_running | |
elif [ "$1" == "start" -a ! -z "$2" ]; then | |
start_vm "$2" | |
elif [ "$1" == "stop" -a ! -z "$2" ]; then | |
stop_vm "$2" | |
elif [ "$1" == "create" -a ! -z "$2" ]; then | |
clone_vm "$2" | |
elif [ "$1" == "destroy" -a ! -z "$2" ]; then | |
destroy_vm "$1" | |
elif [ -z "$1" ]; then | |
list_running | |
echo "Use 'vm list' to list vms or 'vm help' for help" | |
else | |
show_help | |
exit -1 | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment