Skip to content

Instantly share code, notes, and snippets.

@nieldw
Last active March 23, 2017 19:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nieldw/7edb6685bd175393e5ef0b7c748ba6cd to your computer and use it in GitHub Desktop.
Save nieldw/7edb6685bd175393e5ef0b7c748ba6cd to your computer and use it in GitHub Desktop.
Bash script to remove old images in continuous integration (jenkins,teamcity,bamboo,etc) environment. It keeps the provided image (therefore making it available for caching), but removes all older versions of that image.
#!/usr/bin/env bash
usage(){
# ============================================================
echo This script removes all images of the same repository and
echo older than the provided image from the docker instance.
echo
echo This cleans up older images, but retains layers from the
echo provided image, which makes them available for caching.
echo
echo Usage:
echo
echo '$ ./delete-images-before.sh <image-name>:<tag>'
exit 1
# ============================================================
}
[[ $# -ne 1 ]] && usage
IMAGE=$(echo $1 | awk -F: '{ print $1 }')
TAG=$(echo $1 | awk -F: '{ print $2 }')
FOUND=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep ${IMAGE}:${TAG})
if ! [[ ${FOUND} ]]
then
echo The image ${IMAGE}:${TAG} does not exist
exit 2
fi
docker images --filter before=${IMAGE}:${TAG} \
| grep ${IMAGE} \
| awk '{ print $3 }' \
| xargs --no-run-if-empty \
docker --log-level=warn rmi --force || true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment