|
#!/bin/zsh |
|
# Next time this breaks, port it to python! |
|
|
|
echo "Script for cleaning up Docker images" |
|
echo "====================================" |
|
echo "" |
|
|
|
# Run prune before deleting tags to clean up problematic <none> tags |
|
echo "Pruning images" |
|
echo "--------------" |
|
docker system prune -f |
|
echo "" |
|
|
|
|
|
echo "Remove older tags for images" |
|
echo "----------------------------" |
|
# First, we grab a list of all images |
|
docker_images=$(docker images --format "{{.ID}}|{{.Repository}}|{{.Tag}}") |
|
|
|
# prepare a image lookups |
|
declare -A image_ids |
|
declare -A image_tags |
|
|
|
# Then, we loop through the list |
|
while read -r line; do |
|
# We split the line into an array |
|
IFS='|' read -r -A array <<< "$line" |
|
|
|
# We grab the image ID |
|
image_id=${array[1]} |
|
|
|
# We grab the image name |
|
image_name=${array[2]} |
|
|
|
# We grab the image tag |
|
image_tag=${array[3]} |
|
|
|
# We check if the image_name has already been saved in image_ids |
|
if [[ -z "${image_ids[$image_name]}" ]]; then |
|
# If not, we save it |
|
echo "Keeping ${image_name}:${image_tag}" |
|
image_ids[$image_name]=$image_id |
|
image_tags[$image_name]=$image_tag |
|
# If yes, we check if image_id matches and image_tag is older |
|
elif [[ "${image_ids[$image_name]}" == "$image_id" ]] && [[ "${image_tags[$image_name]}" < "$image_tag" ]]; then |
|
# If yes, we delete the saved image |
|
echo "Found newer tag for ${image_name}:${image_tag}" |
|
echo "Deleting ${image_name}:${image_tags[$image_name]}" |
|
docker rmi "${image_name}:${image_tags[$image_name]}" || true # ignore errors (e.g. if image is in use) |
|
# And we save the new image |
|
image_tags[$image_name]=$image_tag |
|
else |
|
# If yes, we remove the image |
|
echo "Deleting ${image_name}:${image_tag}" |
|
docker rmi "${image_name}:${image_tag}" || true # ignore errors (e.g. if image is in use) |
|
fi |
|
done <<< "$docker_images" |
|
echo "" |
|
|
|
# Run prune after deleting tags to clean up layers and cache |
|
echo "Pruning images (again)" |
|
echo "----------------------" |
|
docker system prune -f |
|
echo "" |