Skip to content

Instantly share code, notes, and snippets.

@racsoraul
Last active October 14, 2019 19:43
Show Gist options
  • Save racsoraul/fa47d536e381a1d9c0c69bc4e79a111d to your computer and use it in GitHub Desktop.
Save racsoraul/fa47d536e381a1d9c0c69bc4e79a111d to your computer and use it in GitHub Desktop.
This script helps to stop and/or remove all containers at the same time.
#!/usr/bin/env bash
# Script to help cleaning containers and images.
# Stop and remove commands for containers; delete command for "<none>" images.
# Author: https://github.com/racsoraul
set -o errexit
bold=$(tput bold)
normal=$(tput sgr0)
underline=$(tput smul)
no_underline=$(tput rmul)
case $1 in
-a|--all-containers)
for id in $(docker ps -aq)
do
echo "CONTAINER: $id"
echo -n "Stopping... "
docker container stop "$id" > /dev/null
echo $'\u2714'
echo -n "Removing... "
docker container rm "$id" > /dev/null
echo $'\u2714'
done
;;
-s|--stop-containers)
for id in $(docker ps -aq)
do
echo "CONTAINER: $id"
echo -n "Stopping... "
docker container stop "$id" > /dev/null
echo $'\u2714'
done
;;
-r|--remove-containers)
for id in $(docker ps -aq)
do
echo "CONTAINER: $id"
echo -n "Removing... "
docker container rm "$id" > /dev/null
echo $'\u2714'
done
;;
-i|--remove-none-images)
for id in $(docker image ls | awk '$1 == "<none>" && NR != 1 {print $3}')
do
echo "IMAGE: $id"
echo -n "Removing... "
docker image rm "$id" > /dev/null
echo $'\u2714'
done
;;
*|-h|--help)
echo "${bold}${underline}USAGE:${no_underline} ${normal}${0##*/} ${bold}[OPTIONS]${normal}"
echo
echo "${underline}Stops and removes all docker containers.${no_underline}"
echo
echo "${bold} -h, --help ${normal}shows help for this command"
echo "${bold} -a, --all-containers ${normal}stops and removes all existent containers"
echo "${bold} -s, --stop-containers ${normal}stops all the running containers"
echo "${bold} -r, --remove-containers ${normal}removes all the existent containers"
echo "${bold} -i, --remove-none-images ${normal}removes all '<none>' images"
echo
exit 1
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment