I am trying to build a small script that removes all docker images besides a small "cache" of N last images (for rolling back to one of the last working versions).
Is there an idiomatic way to do this?
You can use the tail
command to accomplish this.
Let's say you only want to keep the most recent 5 images. You can tell tail
to show you the list starting with the nth line. For 5 images, you would want tail to start on the 6th line:
tail -n +6
Pair this with docker to show a list of your image IDs, which are sorted by most recent, by default.
docker images -q | tail -n +6
You can pass all of that to the remove images command. This assumes you're using the bash shell; if you use a csh-derived shell, you may need different syntax.
docker rmi $(docker images -q | tail -n +6)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With