Last active
May 25, 2018 13:44
-
-
Save elasticdog/7fc28e12ab623de7e06a to your computer and use it in GitHub Desktop.
clean up old versions of vagrant boxes
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
#!/usr/bin/env bash | |
##### Functions | |
# print this script's usage message to stderr | |
usage() { | |
cat <<-EOF >&2 | |
usage: vagrant-box-clean [-p PREFIX] [-d] [-h] | |
EOF | |
} | |
# print this script's help message to stdout | |
help() { | |
cat <<-EOF | |
NAME | |
vagrant-box-clean -- clean up old versions of vagrant boxes | |
SYNOPSIS | |
vagrant-box-clean [options...] | |
DESCRIPTION | |
vagrant-box-clean will remove your stale vagrant boxes, leaving just | |
the most recent version of each box. To list all of your existing | |
boxes, use the command "vagrant box list". | |
OPTIONS | |
-p, --prefix=PREFIX | |
only remove boxes named with this prefix | |
-d, --dry-run | |
print the commands that would run, but do not execute | |
-h, --help | |
view this help message | |
AUTHOR | |
Aaron Bull Schaefer <[email protected]> | |
EOF | |
} | |
##### Main | |
# reset all variables that might be set | |
prefix='' | |
dry_run='' | |
# parse command line options | |
while [[ "$1" != '' ]] | |
do | |
case $1 in | |
-p | --prefix) | |
prefix=$2 | |
shift | |
;; | |
--prefix=*) | |
prefix=${1#*=} | |
;; | |
-d | --dry-run) | |
dry_run='true' | |
;; | |
-h | --help | -\?) | |
help | |
exit 0 | |
;; | |
--*) | |
usage | |
exit 1 | |
;; | |
*) | |
usage | |
exit 1 | |
;; | |
esac | |
shift | |
done | |
# escape forward slashes | |
prefix=${prefix//\//\\/} | |
# cache the current vagrant box listing | |
tempfile=$(mktemp /tmp/vagrant-box-clean.XXXXXX) | |
trap 'rm -f "$tempfile"' EXIT | |
vagrant box list > "$tempfile" | |
for box_name in $(awk "/^$prefix/{ print \$1 }" "$tempfile" | sort | uniq); do | |
# remove all versions of $box_name except for the most recent | |
while IFS= read -r box; do | |
box_version=$(echo "${box//[\(\)]/}" | awk '{ print $3 }') | |
if [[ $dry_run ]]; then | |
echo vagrant box remove --force --box-version="${box_version}" "${box_name}" | |
else | |
vagrant box remove --force --box-version="${box_version}" "${box_name}" | |
fi | |
done < <(grep "$box_name" "$tempfile" | sed '$d') | |
done | |
exit 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
vagrant box prune
will also take care of this for you