Skip to content

Instantly share code, notes, and snippets.

@mohd-akram
Last active January 7, 2024 10:38
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mohd-akram/6831334839c775c4c50a086b16ace1da to your computer and use it in GitHub Desktop.
Save mohd-akram/6831334839c775c4c50a086b16ace1da to your computer and use it in GitHub Desktop.
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-x> 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-x" "$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