Skip to content

Instantly share code, notes, and snippets.

@gtrabanco
Created June 10, 2017 13:56
Show Gist options
  • Save gtrabanco/627b43db839f9e143a56d48daf532adb to your computer and use it in GitHub Desktop.
Save gtrabanco/627b43db839f9e143a56d48daf532adb to your computer and use it in GitHub Desktop.
Script to remove all unused and old images of docker from the system
#!/bin/bash
# Remove all the dangling images
DANGLING_IMAGES=$(docker images -qf "dangling=true")
if [[ -n $DANGLING_IMAGES ]]; then
docker rmi "$DANGLING_IMAGES"
fi
# Get all the images currently in use
USED_IMAGES=($( \
docker ps -a --format '{{.Image}}' | \
sort -u | \
uniq | \
awk -F ':' '$2{print $1":"$2}!$2{print $1":latest"}' \
))
# Get all the images currently available
ALL_IMAGES=($( \
docker images --format '{{.Repository}}:{{.Tag}}' | \
sort -u \
))
# Remove the unused images
for i in "${ALL_IMAGES[@]}"; do
UNUSED=true
for j in "${USED_IMAGES[@]}"; do
if [[ "$i" == "$j" ]]; then
UNUSED=false
fi
done
if [[ "$UNUSED" == true ]]; then
echo "Removeing ${i}"
docker rmi "$i"
fi
done
# Extracted from: https://stackoverflow.com/a/37133531
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment