0

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
Deepakvg
  • 71
  • 2
  • 9

1 Answers1

1

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).

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • Thanks for you answer. This is only showing the oldest container ID. But I want to delete everything but the latest. Could you please help. `jenkins@Jenkins-x-x-x-x:/var/lib/jenkins/workspace/devops$ docker images --filter "label=ImageName=devops_SellerInterface" --format '{{.CreatedAt}}\t{{.ID}}' | sort -nr | awk -F '\t' 'END { if(NR>1) print $2 }' 47e46ed43b91` – Deepakvg Nov 04 '22 at 11:31
  • I updated the question slightly; if that still doesn't cut it for you, please _explain_ how it's insufficient. – tripleee Nov 04 '22 at 11:33