Run it

99 lines2.0 KB
Raw
#!/usr/bin/env bash

set -euo pipefail

if ! command -v docker >/dev/null 2>&1; then
    echo "Error: docker command not found."
    exit 1
fi

echo "=== Docker Cleanup ==="
echo
docker system df
echo

confirm() {
    local message="$1"
    read -r -p "$message [y/N]: " answer
    [[ "$answer" =~ ^[Yy]$ ]]
}

echo
echo "Select what you want to clean:"
echo
echo "  1) Stopped containers"
echo "  2) Unused networks"
echo "  3) Dangling images"
echo "  4) All unused images"
echo "  5) Build cache"
echo "  6) Unused volumes"
echo "  7) Everything unused"
echo "  8) Exit"
echo

read -r -p "Choice [1-8]: " choice
echo

case "$choice" in
    1)
        if confirm "Remove all stopped containers?"; then
            docker container prune
        fi
        ;;

    2)
        if confirm "Remove all unused networks?"; then
            docker network prune
        fi
        ;;

    3)
        if confirm "Remove all dangling images?"; then
            docker image prune
        fi
        ;;

    4)
        if confirm "Remove ALL unused images?"; then
            docker image prune -a
        fi
        ;;

    5)
        if confirm "Remove unused build cache?"; then
            docker builder prune
        fi
        ;;

    6)
        echo "WARNING: Volumes may contain persistent application data."
        if confirm "Remove all unused volumes?"; then
            docker volume prune
        fi
        ;;

    7)
        echo "WARNING: This removes all Docker resources that are currently unused."
        echo "This includes unused images, stopped containers, networks, build cache and volumes."
        echo
        if confirm "Continue with full cleanup?"; then
            docker system prune -a --volumes
        fi
        ;;

    8)
        echo "Nothing was removed."
        exit 0
        ;;

    *)
        echo "Invalid choice."
        exit 1
        ;;
esac

echo
echo "=== Docker disk usage after cleanup ==="
docker system df
```

Description

Interactive Bash script for safely cleaning up unused Docker containers, networks, images, build cache, and volumes with confirmation prompts.

Revision history

2 saved

Oct 3, 2026

  1. 07:19
    Current
  2. 07:15