The output of docker images
is really intended for humans, and it's not very parse-friendly. Instead, most Docker commands support a --format
flag using Go templates. As you can see in the images
documentation, you only really care about the .Size
value, so you really want this:
docker images --format "{{.Size}}"
This just gives an output like this:
90.6 MB
If you have multiple images, they will each be on a separate line. I'm going to assume you will only ever have one line, because it vastly simplifies the next steps.
To get rid of the MB
, we can simply use sed
:
docker images --format "{{.Size}}" | sed "s/MB//g"
# => 90.6
But, you probably don't want this for your bash script. Most shells don't support floating point comparisons, so inputting 90.6 would just fail. Instead, let's use bc
to truncate the number first:
docker images --format "{{.Size}}" | sed "s/MB/\/1/g" | bc
# => 90
Note that I've replaced the MB
with a division by 1, which truncates in bc
.
You can then pipe it into a shell script. I tested with this script:
VAR=$(cat)
if [ $VAR -gt "250" ]
then
echo "Image too large"
exit 1
fi
Then run with:
docker images --format "{{.Size}}" | sed "s/MB/\/1/g" | bc | ./check_size.sh
# Exits with 0 (for my example)