cfg/bin/docker-clean
Knut Ahlers 7dafa5c0fc
Also search for image with stripped latest tag
Signed-off-by: Knut Ahlers <knut@ahlers.me>
2018-02-20 22:40:55 +01:00

23 lines
818 B
Bash
Executable file

#!/bin/bash
set -euo pipefail
if [ -e "${HOME}/bin/script_framework.sh" ]; then
source "${HOME}/bin/script_framework.sh"
else
function step { echo $@; }
fi
step "Removing containers created / exited >= ~1h ago..."
CONTAINERS=$(docker ps -a | awk '/(hours?|days?|weeks?|months?) ago\s+(Created|Exited)/{ print $1 }' | xargs)
[ -n "${CONTAINERS}" ] && docker rm ${CONTAINERS}
step "Untagging all images not used by containers..."
PS_OUTPUT=$(docker ps -a)
for img in $(docker images | awk '/^[a-z].*(hours?|days?|weeks?|months?) ago/{ print $1":"$2 }' | grep -v '<none>' | sort | uniq); do
if ! ( echo "${PS_OUTPUT}" | grep -q "\s${img}\s" ) && ! ( echo "${PS_OUTPUT}" | grep -q "\s${img%:latest}\s" ); then
docker rmi --no-prune "${img}"
fi
done
step "Removing dangling images..."
docker image prune -f