-1

Bash script for my Jenkins pipeline remove all docker images by condition:

docker images --format="{{.Repository}} {{.Tag}} {{.ID}}" |
grep -v "latest" |
cut -d ' ' -f3 |
xargs docker rmi -f

But sometimes images list is empty by cut -d ' ' -f3, and I get the error:

"docker rmi" requires at least 1 argument.

UPDATE Output of docker images --format="{{.Repository}} {{.Tag}} {{.ID}}":

adoptopenjdk/openjdk11 latest                5578e7619e88
Nginx                  latest                2622e6cca7eb

How I can rewrite the script for not call xargs docker rmi -f not call if never for remove?

Cyrus
  • 84,225
  • 14
  • 89
  • 153
Pavel
  • 2,005
  • 5
  • 36
  • 68

3 Answers3

2

You should be able to do a two step process, something like:

ids="$(docker images --format='{{.ID}} {{.Tag}}' | awk '!/latest/{print $1}')"
if [[ -n "${ids}" ]] ; then
    for id in ${ids} ; do
        docker rmi -f ${id}
    done
fi

You would normally have to watch out for edge cases if you have white-space in the fields but, since all three of these fields seem to disallow white-space as per the docker doco (try saying that three times fast), that shouldn't be an issue.

You'll notice some other changes:

  • Moved ID to field one in the output just in case there may be spaces in the repository or tag (which would screw up field selection, even though the doco states it's probably not an issue);
  • Combined your grep/cut combo into a single awk (adjusting for the previous bullet point as well); and
  • Removed the repository name from the output, since having a repository name like "populatestandardmachine" will result in that repo being ignored regardless of the tag.
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • Better use an array, and use the proper column – Gilles Quénot Jul 03 '20 at 01:47
  • @Gilles, if you can get the output of a arbitrary command (that *may* contain arbitrary white space) into an array, by all means let me know and I'll add it to the answer, assuming of course there is an actual *problem* with the way I've done it. I suspect it's doable, as all three of those fields disallow white-space as far as I can tell. But I'm not sure why you think I'm using the wrong column, I've both moved the desired column to the start of each line *and* used `$1` to get at it. – paxdiablo Jul 03 '20 at 01:56
2

With GNU xargs.

Add option --no-run-if-empty or -r to your xargs command.

Cyrus
  • 84,225
  • 14
  • 89
  • 153
1

Like this:

while IFS= read -r _ _ img; do
  docker rmi -f "$img"
done < <(
  docker images --format="{{.Repository}} {{.Tag}} {{.ID}}" | grep -v ' latest '
)
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223