5

docker images returns:

REPOSITORY            TAG            IMAGE ID       CREATED             SIZE
<none>                <none>         fcc125757e66   About an hour ago   270 MB

Attempts

docker images | awk '{print $6}' returns:

SIZE
ago
hour
ago
ago
ago

Expected outcome

270 so this could be used in an if statement:

if [ VAR > 250 ] then
   echo "Image too large"
   exit 1
fi
2
  • It looks like you already have a wrapper script framed out, and you're just asking how to get the size of an image. Is that correct? – Xiong Chiamiov Apr 16 '17 at 2:14
  • Unverified: awf -F ´\t' ´{ split(" ",$5,arr); print arr[1]}' – Tensibai Apr 16 '17 at 7:15
7

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.