Search code examples
bashxargs

Conditions in bash


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?


Solution

  • With GNU xargs.

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