Skip to content

Instantly share code, notes, and snippets.

@mohd-akram

mohd-akram/vm.sh

Last active Oct 21, 2020
Embed
What would you like to do?
A shell function to simplify using docker (vagrant-like experience)
# Add to ~/.profile or ~/.bashrc, etc
# Use it like:
# vm add ubuntu # or vm add ubuntu custom/ubuntu
# vm sh ubuntu
# <ctrl-d> to detach from shell
# vm sh ubuntu # returns to the same shell
# vm stop ubuntu && vm rm ubuntu
vm() {
case $1 in
ls) docker ps -a ;;
stop) shift; docker stop "$1" >/dev/null ;;
update) shift; docker pull "$1" ;;
rm)
shift
printf "remove vm %s?" "$1" >&2; read
docker rm "$1" >/dev/null ;;
add)
shift
if docker container inspect "$1" >/dev/null 2>&1; then
echo vm "$1" already exists >&2; return 1
fi
if ! docker image inspect "${2-$1}" >/dev/null 2>&1; then
docker pull "${2-$1}"
fi
docker create -it --name "$1" "${2-$1}" /bin/bash >/dev/null ;;
sh)
shift
docker start "$1" >/dev/null &&
if [ $# -gt 1 ]; then (
t=$([ -t 0 ] && echo t || :); n=$1; shift
exec docker exec -i$t "$n" /bin/bash "$@"
) else
docker attach --detach-keys="ctrl-d" "$1"
fi ;;
*)
printf "usage: vm ls\n%s\n" \
"$(printf " vm %s\n" \
"rm name" \
"stop name" \
"sh name [arg ...]" \
"update image" \
"add name [image]")" >&2
return 1
esac
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment