脚本clean_docker_images.sh
#!/bin/bash
#"awk '{print $3}'"只要第三列,"sed -n '2,$p'"从第二行到最后一行,"sort -k2n"排序,"uniq"去重
image_id_arr=$(docker images | awk '{print $3}' | sed -n '2,$p' | sort -k2n | uniq)
white_list=$@
for val in $image_id_arr
do
if [ "$white_list" ];then
if [[ ! "${white_list[@]}" =~ "$val" ]]; then
docker rmi -f $val
if [ $? -ne 0 ]; then
echo "failed to remove image:["$val"], skipped and remove next one!"
continue;
fi
fi
else
docker rmi -f $val
if [ $? -ne 0 ]; then
echo "failed to remove image:["$val"], skipped and remove next one!"
continue;
fi
fi
done;
用法:
#1. 删除所有镜像
$ sh clean_docker_images.sh
#2. 白名单删除镜像(tag为5890f8ba95f6和300e315adb2f的镜像将不会被删除)
$ sh clean_docker_images.sh 5890f8ba95f6 300e315adb2f