xargs

Stopping Docker containers via fuzzy matching on the name

I recently needed to hack together a setup where Docker containers are spawned by an automated process, then later, a garbage collector runs and kills off all spawned containers. This is on a system where there could be anywhere from tens to hundreds of containers running at any given moment, and I needed traceability of different containers while they're running.

One of the easiest ways to have at-a-glance traceability is to have named containers, e.g. spawned-worker-1, spawned-worker-2, etc.

So if I do a docker ps --format '{{.Names}}', I can get a full list of all running containers by name. And then if I want to filter that list to only show me spawned-worker- prefixed container names, I can pipe the output through grep, awk, and xargs to use the container names in a Docker command, like so:

docker ps --format '{{.Names}}' | grep "^spawned-worker-" | awk '{print $1}' | xargs -I {} docker stop {}

In this case, I'm stopping all containers with spawned-worker- as the start of the name.

Remove ALL your local Vagrant Boxes via this bash command

Assuming you have only one box per provider, this command will delete ALL Vagrant boxes you currently have on your system:

$ vagrant box list | cut -f 1 -d ' ' | xargs -L 1 vagrant box remove -f

This command does the following:

  1. vagrant box list: Prints out a list of all installed vagrant boxes (with two columns—box name or path, and meta info)
  2. cut -f 1 -d ' ': Cuts the list and takes out just the first column (using spaces to delimit the columns)
  3. xargs -L 1 vagrant box remove -f: Use xargs to run one command per line, running the command vagrant box remove -f [box name from list/cut].

You can use xargs' -t option to output the commands being run just before they're executed. And if you have multiple boxes per provider, or if you have multiple versions of the same box, you'll likely need to modify the command a bit.