Skip to content

Instantly share code, notes, and snippets.

@dtrugman
Last active October 25, 2021 18:57
Show Gist options
  • Save dtrugman/2ba314ac658489e77f2e9476803e1445 to your computer and use it in GitHub Desktop.
Save dtrugman/2ba314ac658489e77f2e9476803e1445 to your computer and use it in GitHub Desktop.
Interactive Vagrant menu
#!/bin/bash
# This is a helper script for using vagrant interactively
# Just run it without any parameters and follow the menu
ivagrant() {
declare vm_idx="$1"
declare vm_cmds="${@:2}"
# Read records
declare -a vm_records=()
xIFS=$IFS
IFS=$'\n'
for line in $(vagrant global-status); do
declare dir="$(echo $line | awk '{print $5}')"
if [[ "${dir:0:1}" == "/" && -d "$dir" ]]; then
vm_records+=($line)
fi
done
IFS=$xIFS
declare -a vm_ids=()
declare idx=0
declare -r xIFS="$IFS"
IFS=$'\n'
vm_records=($(printf '%s\n' "${vm_records[@]}" | sort -k1))
for vm in ${vm_records[@]}; do
((idx++))
echo "$idx. $vm"
vm_ids+=($(echo $vm | awk '{print $1}'))
done
IFS="$xIFS"
if [[ $idx -eq 0 ]]; then
echo "No available boxes"
return 1
fi
# Get index
if [[ -z "$vm_idx" ]]; then
printf "Which? [1-$idx] "
read vm_idx
fi
if [[ $vm_idx -lt 1 || $vm_idx -gt ${#vm_ids[@]} ]]; then
echo "Bad selection!"
return 1
fi
# Let user choose command
if [[ -z "$vm_cmds" ]]; then
printf "Which command? "
read temp_cmd
vm_cmds=($temp_cmd)
fi
# Use default command in none specified
declare -r vm_cmds_default="ssh"
if [[ -z "$vm_cmds" ]]; then
echo "Using default command [$vm_cmds_default]"
vm_cmds="$vm_cmds_default"
fi
# Execute
for vm_cmd in $vm_cmds; do
vagrant "$vm_cmd" "${vm_ids[$vm_idx - 1]}"
done
}
[[ "$0" == "$BASH_SOURCE" ]] && ivagrant "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment