Skip to content

Instantly share code, notes, and snippets.

@saderi
Created December 12, 2023 13:01
Show Gist options
  • Save saderi/7675ae1ddba28de279bee5ecdb6ae942 to your computer and use it in GitHub Desktop.
Save saderi/7675ae1ddba28de279bee5ecdb6ae942 to your computer and use it in GitHub Desktop.
This script will delete all but the last 5 versions of a docker image from the local machine (not from the registry)
#!/bin/bash
IMAGE_NAME=$1
VERSIONS_TO_KEEP=5
TOTAL_VERSIONS=$(docker image ls | grep $IMAGE_NAME | grep -v latest | wc -l)
VERSIONS_TO_DELETE=$((TOTAL_VERSIONS - VERSIONS_TO_KEEP))
if [ $VERSIONS_TO_DELETE -gt 0 ]; then
echo "Deleting $VERSIONS_TO_DELETE old versions"
docker image ls | grep $IMAGE_NAME | grep -v latest | tail -n $VERSIONS_TO_DELETE | awk '{print $3}' | xargs docker image rm
else
echo "No old versions to delete"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment