#!/bin/bash set -e docker_ps_opts="" dry_run=false hours="10" OPTS="`getopt -o v -l docker_ps_opts:,dry_run,hours: -- "$@"`" while test $# -gt 1; do case $1 in --docker_ps_opts) docker_ps_opts="$2"; shift ;; --dry_run) dry_run="$2"; shift ;; --hours) hours="$2"; shift ;; -v) set -x ;; esac shift done if [ "$hours" -lt "1" ]; then echo "ERROR: Refusing to delete containers that are $hours days old" exit 1 fi echo "Container report before:" docker ps $docker_ps_opts rm_containers=() for container in $(docker ps --format "{{.ID}} {{.RunningFor}}" $docker_ps_opts | grep "hour" | cut -d" " -f 1); do if [ "$(docker ps --format "{{.ID}} {{.RunningFor}}" $docker_ps_opts | grep "$container:" | cut -d" " -f 2)" -gt "$hours" ]; then rm_containers=("${rm_containers[@]}" $container) fi done status="0" if [ ${#rm_containers[@]} != 0 ]; then echo "Removing containers: ${rm_containers[@]}" if ! $dry_run; then for container in "${rm_containers[@]}"; do echo "Removing container $container" docker rm -f -v $container | true if [ x"${PIPESTATUS[0]}" = x"0" ]; then echo "SUCCESS" else echo "FAILED" status="1" fi done else echo "DRY_RUN: NOT REMOVING CONTAINERS" status="1" fi echo "Containers report after:" docker ps $docker_ps_opts fi exit $status