Last active
July 23, 2018 15:57
-
-
Save leibowitz/7e0968a974588d3367bf70b79d552a64 to your computer and use it in GitHub Desktop.
Delete docker images
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
SAVEIFS=$IFS | |
DANGLING=`docker images -f dangling=true | grep -v REPOSITORY | tr -s ' ' | cut -d' ' -f3` | |
IFS=$'\n' | |
DANGLING=($DANGLING) | |
IFS=$SAVEIFS | |
if [ ${#DANGLING[@]} -gt 0 ]; then | |
echo ${#DANGLING[@]} "dangling images to delete:" | |
echo ${DANGLING[*]} | |
docker rmi ${DANGLING[*]} | |
echo ${#DANGLING[@]} "images deleted" | |
elif [ $# -lt 1 ]; then | |
echo "Please pass the name of the images to delete as argument:" | |
echo | |
echo "usage:" $0 IMAGE [IMAGE...] | |
exit 1 | |
fi | |
declare -a TAGS | |
declare -a IMAGES | |
for ARG in $@; do | |
echo "Looking for $ARG images" | |
IMAGES=`docker images | grep -v REPOSITORY | grep $ARG` | |
TAGS=`echo "$IMAGES" | tr -s ' ' | cut -d' ' -f2 | sort -rn | head -n2` | |
IFS=$'\n' | |
TAGS=($TAGS) | |
IFS=$SAVEIFS | |
if [ ${#TAGS[@]} -eq 0 ]; then | |
echo "No tag found, nothing to delete" | |
continue | |
elif [ ${#TAGS[@]} -lt 2 ]; then | |
echo ${#TAGS[@]} "Tags found:" ${TAGS[*]} | |
echo "Only" ${#TAGS[@]} "tag found, nothing to delete" | |
continue | |
fi | |
echo ${#TAGS[@]} "Tags found:" ${TAGS[*]} | |
#echo "Filtering through images:" | |
#echo "$IMAGES" | |
for TAG in ${TAGS[*]}; do | |
IMAGES=`echo "$IMAGES" | grep -v $TAG` | |
done | |
TODELETE=`echo "$IMAGES" | tr -s ' ' | cut -d' ' -f3 | xargs -I% echo % | sort -u` | |
IFS=$'\n' | |
TODELETE=($TODELETE) | |
if [ ${#TODELETE[@]} -eq 0 ]; then | |
echo "No images to delete" | |
continue | |
fi | |
echo ${#TODELETE[@]} "images to delete:" | |
echo ${TODELETE[*]} | |
docker rmi ${TODELETE[*]} | |
IFS=$SAVEIFS | |
echo ${#TODELETE[@]} "images deleted" | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment