Skip to content

Instantly share code, notes, and snippets.

@hedzr
Last active September 1, 2022 06:29
Show Gist options
  • Save hedzr/f16f6f2b13a4a2c83d4ac92226749373 to your computer and use it in GitHub Desktop.
Save hedzr/f16f6f2b13a4a2c83d4ac92226749373 to your computer and use it in GitHub Desktop.
Bash/Zsh script for running VM in headless mode (VMWare Fusion or VMWare)

Paste the content into your .zshrc or .bashrc, and relogin.

# $ vmware_run help
# Usage:
#  vmware_run <VM-name> <start|stop|suspend|reset|pause|unpause>
#  vmware_run <VM-name> <start_with_gui|start-with-gui>
#
# Examples:
#  vmware_run start u20.local.new
#  # start vm without gui (headless mode)
#
# $ vmware_run u20.local.new start && sleep 5 && ssh u20.local
# ....
#
# $ vmware_run u20.local.new suspend

vmware_run(){
	local VMDIR="$HOME/Downloads/VMs/vmware"
	local VMTYPE=fusion # or "ws"
	# local VMDIR="$HOME/Documents/Virtual Machines.localized"
	which vmrun >/dev/null 2>&1 || ln -s "/Applications/VMware Fusion.app/Contents/Library/vmrun" /usr/local/bin/vmrun
	case $2 in
		start)
			local cmd=$2 && local vmn=$1 && shift && shift && vmware_run_start $cmd $vmn nogui "$@"
			;;
		start_with_gui|start-with-gui|unpause)
			local cmd=$2 && local vmn=$1 && shift && shift && vmware_run_start start $vmn "$@"
			;;
		stop|suspend|reset|pause)
			local cmd=$2 && local vmn=$1 && shift && shift && vmware_run_stop $cmd $vmn nogui "$@"
			;;
		*)
			case $1 in
				usage|help)
					cat <<-EOF
					Usage:
					  $(basename $0) <VM-name> <start|stop|suspend|reset|pause|unpause>
					  $(basename $0) <VM-name> <start_with_gui|start-with-gui>

					Examples:
					  $(basename $0) start u20.local.new
					  # start vm without gui (headless mode)

					EOF
					;;

				*)
					vmrun "$@"
					;;
			esac
			;;
	esac
}
vmware_run_start () {
	local cmd=$1
	local vmname=$2
	shift; shift
	vmrun list | grep -q "$vmname" && {
		echo "VM '$vmname' already running"
	} || {
		vmrun -T $VMTYPE $cmd $VMDIR/$vmname.vmwarevm/$vmname.vmx "$@"
	}
}
vmware_run_stop () {
	local cmd=$1
	local vmname=$2
	vmrun list | grep -q "$vmname" || {
		echo "VM '$vmname' not running"
	} && {
		vmrun -T $VMTYPE $cmd $VMDIR/$vmname.vmwarevm/$vmname.vmx
	}
}

Feel free.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment