I have script that stops containers and then removes them
docker stop $(docker ps -q) docker rm $(docker ps -a -q)
But I don't want to remove the docker container with name "my_docker".
How can I remove all containers except this one?
You can try this, which will
grep -v
), and thenRun this command:
docker rm $(docker ps -a | grep -v "my_docker" | awk 'NR>1 {print $1}')
To use cut
instead of awk
, try this:
docker rm $(docker ps -a | grep -v "my_docker" | cut -d ' ' -f1)
Examples for awk
/cut
usage here: bash: shortest way to get n-th column of output
The title of the question asks for images, not containers. For those stumbling across this question looking to remove all images except one, you can use docker prune along with filter flags:
docker image prune -a --force --filter "label!=image_name"
replacing image_name with the name of your image.
You can also use the "until=" flag to prune your images by date.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With