Skip to content

Instantly share code, notes, and snippets.

@cmizzi
Last active January 13, 2021 15:45
Show Gist options
  • Select an option

  • Save cmizzi/7e1ebb83d1ce233e6d49dd7d9ed51a6f to your computer and use it in GitHub Desktop.

Select an option

Save cmizzi/7e1ebb83d1ce233e6d49dd7d9ed51a6f to your computer and use it in GitHub Desktop.
Docker function to easily connect and log containers/services
#!/bin/bash
# Show container log.
dl() {
if [ "$1" = "service" ]; then
docker service logs -f --tail 100 $2
return
fi;
docker logs -f --tail 100 $2
}
# Shortcut to log in container/service
dockershell() {
if [ "$1" = "service" ]; then
ID=$(docker inspect --format '{{.Status.ContainerStatus.ContainerID}}' $(docker service ps -q "$2" | head -1))
else
ID=$2
fi;
CMD=$3
if [ -z $CMD ]; then
# try using bash by default : if not found, fallback on sh
CMD="command -v bash > /dev/null 2>&1 && bash --noprofile || sh"
fi
docker exec -t -i -e PS1="$ID:\w# " "$ID" sh -c $CMD
}
__dockershell() {
local state
_arguments \
"1: :->kind" \
"*: :->containers" \
case $state in
(kind) compadd "$@" service container ;;
(*)
if [ "$words[2]" = "service" ]; then
_arguments "*:services:($((docker info 2> /dev/null | grep -i 'swarm: active') && docker service ls -q --format '{{.Name}}'))"
else
_arguments "*:containers:($(docker ps -q --format '{{.Names}}'))"
fi;
;;
esac
}
compdef __dockershell dl
compdef __dockershell dockershell
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment