Home > Blockchain >  How to avoid getting an error message when there is no docker container/image/volume to remove?
How to avoid getting an error message when there is no docker container/image/volume to remove?

Time:12-17

So currently in my pipeline I need to remove all previous docker containers, images and volumes, and for that I run:

docker stop $(docker ps -q)
docker rm -f $(docker ps -a -q)
docker volume rm $(docker volume ls -q)
docker rmi -f $(docker images -q)

But if for some reason, there was already any volume (or container or image), the command line returns the error: docker volume rm requires at least 1 argument.

And of course the pipeline breaks: See the error in my pipeline

I've tried adding a line in the pipeline before, so I will always have at least one docker container/volume/image to remove, but I know this is not a good practice.

I need a command so if there is no container/volume/image, returns a 'nothing to remove' message and continues without breaking the pipeline.

Thanks!


Edit: Thanks to larsks suggestion, I ended up using:

docker ps -q | xargs --no-run-if-empty docker container stop
docker ps -a -q | xargs --no-run-if-empty docker container rm
docker volume ls -q | xargs --no-run-if-empty docker volume rm
docker images -q | xargs --no-run-if-empty docker image rm

This completely fixed my Pipeline.

CodePudding user response:

You can use xargs, for example:

docker volume ls -q | xargs --no-run-if-empty docker volume rm

This will not run the docker volume rm command if docker volume ls -q produces no output.

  • Related