Skip to content

Instantly share code, notes, and snippets.

@DeamonMV
Last active April 3, 2018 13:21
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 DeamonMV/431288939d161a28652eb2f993c0f45f to your computer and use it in GitHub Desktop.
Save DeamonMV/431288939d161a28652eb2f993c0f45f to your computer and use it in GitHub Desktop.
Script which is perform deletion of docker images
#!/bin/bash
if [ "$#" -eq "0" ]; then
echo "Need to specify docker image name"
echo "In case if you want to see how much images do you have, just specify image name"
echo "Also need to specify count of lines(i.e. count of images) which will be saved"
echo "Should be something like this: docker-image-deletion.sh 'jenkins' 2"
exit 1
fi
NUM="^[0-9]+&"
COUNT=$(docker images | grep "^$1 " | wc -l)
if [ "$#" -eq "2" ] || [[ "$2" =~ "$NUM" ]]; then
if [ "$2" -ge "$COUNT" ]; then
echo "Wrong number to save images. Count images to save should be less than exist"
exit 1
fi
DELETE_IMAGES=`expr $COUNT - $2`
echo "Images which will be deleted"
echo "=============================================================="
docker images | grep "^$1 " | tail -n $DELETE_IMAGES
echo -e "\n\nImages which will be saved"
echo "=============================================================="
docker images | grep "^$1 " | head -n $2
read -p"Do you want to procced?[y/n]" ANSWER </dev/tty
if [ "${ANSWER}" == "n" ] || [ "${ANSWER}" == "" ];then
exit 1
fi
docker images | grep "^$1 " | tail -n $DELETE_IMAGES | awk '{print $3}' | xargs -d'\n' docker image rm
else
echo "Images which are available:"
echo "=============================================================="
docker images | grep "^$1 "
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment