Shell script for docker ps -a | grep to find number of certain containers running

Solution 1:

The following script should do what you want :

#!/bin/bash

name=$1

matchingStarted=$(docker ps --filter="name=$name" -q | xargs)
[[ -n $matchingStarted ]] && docker stop $matchingStarted

matching=$(docker ps -a --filter="name=$name" -q | xargs)
[[ -n $matching ]] && docker rm $matching

Basically, it checks if there is a running container with the provided name, and stop it if it find one. Then, it remove any container with the provided name.

Note: You may want to add some argument validation, as if used without argument, this script will stop all running containers and delete all stopped containers. I did not add it here to keep it simple and easily readable.

Solution 2:

You have to take into account at least two cases - removing stopped container, which can be removed with a single command and removing running containers, where the container has to be stopped first before being deleted.

In addition to this, in stead of using grep to find the container name, I would use the filter option of docker ps, that way you won't end up grepping the wrong container just because say the command option matches the name you placed in grep. Here is how I would remove any similar docker containers, strictly follow the below sequence -

  1. Remove running containers
for container_id in $(docker ps  --filter="name=$name" -q);do docker stop $container_id && docker rm $container_id;done
  1. Remove stopped containers, since we have stopped running containers in step 1.
for container_id in $(docker ps  --filter="name=$name" -q -a);do docker rm $container_id;done

The -a option will include all containers, including the stopped ones. Not using -a, the default option, will include only running containers. So on step one, you remove the running containers, and then on step two you proceed with the stopped ones. To remove or stop a container, all you need is the container id, the -q options outputs only the ID.