Skip to content

Instantly share code, notes, and snippets.

@graemian
Forked from eduardocardoso/gist:82a629882ddb02ab3677
Last active September 24, 2015 07:08
Show Gist options
  • Save graemian/fdf32edf1592d1cea944 to your computer and use it in GitHub Desktop.
Save graemian/fdf32edf1592d1cea944 to your computer and use it in GitHub Desktop.
#!/bin/bash
set -o errexit
echo "Removing exited docker containers..."
docker ps -a -f status=exited -q | grep -vE "$(docker ps -a --filter='name=-data' -q | tr \"\n\" \|)" | xargs -r docker rm -v
echo "Removing untagged images..."
docker images --no-trunc | grep "<none>" | awk '{print $3}' | xargs -r docker rmi
echo "Removing unused docker images"
images=($(docker images | tail -n +2 | awk '{print $1":"$2}'))
containers=($(docker ps -a | tail -n +2 | awk '{print $2}'))
containers_reg=" ${containers[*]} "
remove=()
for item in ${images[@]}; do
if [[ ! $containers_reg =~ " $item " ]]; then
remove+=($item)
fi
done
remove_images=" ${remove[*]} "
echo ${remove_images} | xargs -r docker rmi
echo "Done"
@Vishant0031
Copy link

containers=($(docker ps -a | tail -n +2 | awk '{print $2}'))
ps -a would include exited containers also and if container is exited the respective image can as well be deleted. ??

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment