I want to delete non latest intermediate image with the label from docker. I used the below command, it works if there is more than 1 image, but if there is exactly 1 image, then it is deleting that image and again caching will happen from the next build. I'm new to Bash Scripting, any help would be highly appreciated.
What I want
if image_ids_with_label>1:
delete_nonlatest_images
else:
pass
Bash Command
docker images --filter "label=ImageName="$LabelName --format '{{.CreatedAt}}\t{{.ID}}' | sort -nr | tail -n -1 | cut -f2 | xargs --no-run-if-empty sudo docker rmi
CodePudding user response:
A good fix is probably to replace the pipeline with a simple Awk script which doesn't print anything if there is only one line.
docker images --filter "label=ImageName=$LabelName" --format '{{.CreatedAt}}\t{{.ID}}' |
sort -nr |
awk -F '\t' 'END { if(NR>1) print $2 }' |
xargs --no-run-if-empty sudo docker rmi
Also notice how you want $LabelName
inside the quotes, just in case it contains a shell metacharacter. (See also When to wrap quotes around a shell variable.)
Your attempt used tail -n -1
which only prints the last line; if you really wanted to print all the lines except the first, that would be
awk -F '\t' 'NR>1 { print $2 }'
(and the corresponding tail
invocation would be tail -n 2
).